ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Python] - Iterators
    개발/Python 2022. 7. 27. 15:01

    Iterators


    An iterator is an object that contains a countable number of values.
    An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
    Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__().

     

    iterable

    • Lists, tuples, dictionaries, and sets are all iterable objects.
    • They are iterable containers which you can get an iterator from.
    • All these objects have a iter() method which is used to get an iterator
    mytuple = ("1", "2", "3")
    myit = iter(mytuple)
    
    print(next(myit))
    > 1
    print(next(myit))
    > 2
    print(next(myit))
    > 3
    • We can also use a for loop to iterate through an iterable object
    mytuple = ("1", "2", "3")
    
    for x in mytuple:
      print(x)

     

    Create Iterator


    • To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object.
    • The __iter__() method acts similar, you can do operations (initializing etc.), but must always return the iterator object itself.
    • The __next__() method also allows you to do operations, and must return the next item in the sequence.
    class MyNumbers:
      def __iter__(self):
        self.a = 1
        return self
    
      def __next__(self):
        x = self.a
        self.a += 1
        return x
    
    myclass = MyNumbers()
    myiter = iter(myclass)
    
    print(next(myiter))
    print(next(myiter))

    StopIteration


    • if you had enough next() statements, or if it was used in a for loop.
    • To prevent the iteration to go on forever, we can use the StopIteration statement.
    class MyNumbers:
      def __iter__(self):
        self.a = 1
        return self
    
      def __next__(self):
        if self.a <= 20:
          x = self.a
          self.a += 1
          return x
        else:
          raise StopIteration

    '개발 > Python' 카테고리의 다른 글

    [Python] - Regular expression  (0) 2022.07.27
    [Python] - Sort / Reverse  (0) 2022.07.27
    [Python] - Function , Lambda  (0) 2022.07.27
    [Python] - Powerful Function  (0) 2022.07.27
    [Python] - Set  (0) 2022.07.27

    댓글

Designed by Tistory.