The iter() method creates an object which can be iterated one element at a time.
These objects are useful when coupled with loops like for loop, while loop.
The syntax of iter() method is:
iter(object[, sentinel])
Recommended Reading: Python iterators and how to work with them.
The iter() method takes two parameters:
Depending upon the arguments passed, iter() must have the following attributes.
The iter() method returns iterator object for the given object that loops through each element in the object.
In case of sentinel provided, it returns the iterator object that calls the callable object until the sentinel character isn't found.
# list of vowels vowels = ['a', 'e', 'i', 'o', 'u'] vowelsIter = iter(vowels) # prints 'a' print(next(vowelsIter)) # prints 'e' print(next(vowelsIter)) # prints 'i' print(next(vowelsIter)) # prints 'o' print(next(vowelsIter)) # prints 'u' print(next(vowelsIter))
When you run the program, the output will be:
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 printNum = PrintNumber(3) printNumIter = iter(printNum) # prints '1' print(next(printNumIter)) # prints '2' print(next(printNumIter)) # prints '3' print(next(printNumIter)) # raises StopIteration print(next(printNumIter))
1 2 3 StopIteration
with open('mydata.txt') as fp: for line in iter(fp.readline, ''): processLine(line)
When you run the program, it will open mydata.txt in read mode.
Then, the iter(fp.readline, '') in the for loop calls readline (which reads each line in the text file) until the sentinel character '' (empty string) is reached.
iter(fp.readline, '')
readline