The python iter function is used to return an iterator for the object. The iter() is used to create an object that will iterate one element at a time. The iter() takes two optional arguments as input.
The syntax of the iter() function is:
iter(object, sentinel)
iter() Parameters
The python iter() takes 2 optional parameters. The two optional parameters are:
- object- this parameter is the object whose iterator must be created (tuples, sets, and so on)
- sentinel- a unique value that represents the end of a sequence
Return value from iter()
For the provided object, the iter() function returns an iterator object.
The TypeError exception is raised if the user-defined function does not implement the _next_(), the _iter_(), or the _getitem()_.
Iter() produces an iterator until the sentinel character isn’t found if the sentinel parameter is also provided.
Example 1: Working of Python iter()
# 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
Example 2: iter() for custom objects
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
Example 3: iter() with sentinel parameter
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
What is ITER () in Python?
The iter() function in Python is used to transform an iterable into an iterator.
Program to demonstrate the iter()
Source Code
listt1 = [1, 2, 3, 7, 5]
# printing type
print ("The list is of type : " + str(type(listt1)))
# converting list using iter()
lis1 = iter(listt1)
# printing type
print ("The iterator is of type : " + str(type(listt1)))
# using next() to print iterator values
print (next(listt1))
print (next(listt1))
print (next(listt1))
print (next(listt1))
print (next(listt1))
Output:
The list is of type :
The iterator is of type :
1
2
3
7
5
What are iterations in Python?
Iterations are statements that allow us to execute a set of statements. There are three types of iteration statements in Python, the while loop, for loop, and the nested for loops. Iterable objects include lists, tuples, dictionaries, and sets.
How does __ ITER __ work in Python?
The _iter_() in Python is used to return an iterator object each element at a time.
Here are some examples for the use of the iter() in python:
Example 1:
lst123 = [11, 22, 33, 44, 55]
iter_lst = iter(lst123)
while True:
try:
print(iter_lst.__next__())
except:
break
Output:
11
22
33
44
55
Example 2:
listB1 = ['Catto', 'Bats', 'Satt', 'Matt']
iter_listB1 = listB1.__iter__()
try:
print(iter_listB1.__next__())
print(iter_listB1.__next__())
print(iter_listB1.__next__())
print(iter_listB1.__next__())
print(iter_listB1.__next__()) #StopIteration error
except:
print(" \nThrowing 'StopIterationError'",
"There is nothing more in the list")
Output :
Catto
Bats
Satt
Matt
Throwing 'StopIterationError' There is nothing more in the list.
Example 3: Users can implement the iter() with the help of OOPs
Source Code:
class Counter:
def __init__(self, start, end):
self.num = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.num > self.end:
raise StopIteration
else:
self.num += 1
return self.num - 1
# Driver code
if __name__ == '__main__' :
a, b = 2, 5
c1 = Counter(a, b)
c2 = Counter(a, b)
# Way 1-to print the range without iter()
print ("Print the range without iter()")
for i in c1:
print ("Can't wait for the weekend to start", i, end ="\n")
print ("\nPrint the range using iter()\n")
# Way 2- using iter()
obj1 = iter(c2)
try:
while True: # Print till error raised
print ("Can't wait for the weekend to start", next(obj1))
except:
#Print custom message when StopIteration is raised.
print ("\nSaturday is finally here!!")
Output :
Print the range without iter()
Can't wait for the weekend to start, counting 2
Can't wait for the weekend to start, counting 3
Can't wait for the weekend to start, counting 4
Can't wait for the weekend to start, counting 5
Print the range using iter()
Can't wait for the weekend to start, counting 2
Can't wait for the weekend to start, counting 3
Can't wait for the weekend to start, counting 4
Can't wait for the weekend to start, counting 5
Saturday is finally here!!
How do I make Python iterable?
The classes in Python are by default not iterable. To make an iterable class in python, the user has to implement the _iter_().
This function allows the method to make operations or initialize the items and return the iterator’s object. Along with the _iter_(), the _next_() is used to print the next item in the sequence.
Leave a Reply