in Technology by
What are iterators in Python?

1 Answer

0 votes
by
  • Iterator is an object.
  • It remembers its state i.e., where it is during iteration (see code below to see how)
  • __iter__() method initializes an iterator.
  • It has a __next__() method which returns the next item in iteration and points to the next element. Upon reaching the end of iterable object __next__() must return StopIteration exception.
  • It is also self iterable.
  • Iterators are objects with which we can iterate over iterable objects like lists, strings, etc.
class ArrayList:
    def __init__(self, number_list):
        self.numbers = number_list

    def __iter__(self):
        self.pos = 0
        return self

    def __next__(self):
        if(self.pos < len(self.numbers)):
            self.pos += 1
            return self.numbers[self.pos - 1]
        else:
            raise StopIteration

array_obj = ArrayList([1, 2, 3])

it = iter(array_obj)

print(next(it)) #output: 2
print(next(it)) #output: 3

print(next(it))
#Throws Exception
#Traceback (most recent call last):
#...
#StopIteration

Related questions

0 votes
    Which of these iterators can be used only with List? (a) Setiterator (b) ListIterator (c) Literator (d ... Framework of Java Select the correct answer from above options...
asked Mar 1, 2022 in Education by JackTerrance
0 votes
    Which of these iterators can be used only with List? (a) Setiterator (b) ListIterator (c) Literator ... questions and answers pdf, java interview questions for beginners...
asked Oct 25, 2021 in Education by JackTerrance
0 votes
    What are the values of the following Python expressions? 2**(3**2) (2**3)**2 2**3**2 a) 512, 64, 512 b) 512, 512, 512 c) 64, 512, 64 d) 64, 64, 64...
asked Dec 31, 2022 in Technology by JackTerrance
0 votes
    What are builtin Data Types in Python?...
asked Aug 20, 2021 in Technology by JackTerrance
0 votes
    What are the supported data types in Python?...
asked Apr 24, 2021 in Technology by JackTerrance
0 votes
    What are the Difference between staticmethod and classmethod in Python?...
asked Jan 9, 2021 in Technology by JackTerrance
0 votes
    What are metaclasses in Python?...
asked Jan 9, 2021 in Technology by JackTerrance
0 votes
    How are arguments passed by value or by reference in python?...
asked Dec 7, 2020 in Technology by JackTerrance
0 votes
    What are unittests in Python?...
asked Dec 7, 2020 in Technology by JackTerrance
0 votes
    What are generators in Python?...
asked Dec 6, 2020 in Technology by JackTerrance
0 votes
    What are global, protected and private attributes in Python?...
asked Dec 6, 2020 in Technology by JackTerrance
0 votes
    What are modules and packages in Python?...
asked Dec 6, 2020 in Technology by JackTerrance
0 votes
    What are the common built-in data types in Python?...
asked Dec 6, 2020 in Technology by JackTerrance
0 votes
    What are decorators in Python?...
asked Dec 6, 2020 in Technology by JackTerrance
...