The python iter() function helps to return an iterator. An iterator is an object which means it contains a number of values that can be countable. An iterator can traverse through all the values. These objects are useful with loops like for loop, while loop etc. The iter() object iterates one element at a time.
iter(object, sentinel) # object can be sets,tuples etc
Takes 2 parameters where a first parameter is an object that can be sets, tuples, etc.
Parameter | Description | Required / Optional |
---|---|---|
object | an object whose iterator has to be created | Required |
sentinel | special value that is used to represent the end of a sequence. | Optional |
If the user-defined object doesn't implement __iter__()
, and __next__()
or __getitem()__
, the TypeError exception is raised. If the sentinel parameter is also provided, iter() returns an iterator until the sentinel character isn't found.
Input | Return Value |
---|---|
objects and sentinel are given | iterator |
# list of vowels
vowels = ['a', 'e', 'i', 'o', 'u']
vowels_iter = iter(vowels)
print(next(vowels_iter)) # 'a'
print(next(vowels_iter)) # 'e'
print(next(vowels_iter)) # 'i'
print(next(vowels_iter)) # 'o'
print(next(vowels_iter)) # 'u'
Output:
a e i o u
class PrintNumber:
def __init__(self, max):
self.max = max
def __iter__(self):
self.num = 0
return self
def __next__(self):
if(self.num >= self.max):
raise StopIteration
self.num += 1
return self.num
print_num = PrintNumber(3)
print_num_iter = iter(print_num)
print(next(print_num_iter)) # 1
print(next(print_num_iter)) # 2
print(next(print_num_iter)) # 3
# raises StopIteration
print(next(print_num_iter))
Output:
1 2 3 Traceback (most recent call last): File "", line 23, in File "", line 11, in __next__ StopIteration
class DoubleIt:
def __init__(self):
self.start = 1
def __iter__(self):
return self
def __next__(self):
self.start *= 2
return self.start
__call__ = __next__
my_iter = iter(DoubleIt(), 16)
for x in my_iter:
print(x)
Output:
2 4 8