Python Iterator Example
Chapter:
Python
Last Updated:
12-11-2021 14:20:54 UTC
Program:
/* ............... START ............... */
person = ("John", "james", "mathew")
entries = iter(person)
print(next(entries))
print(next(entries))
print(next(entries))
/* Output
John
james
mathew
*/
str = "Iterator"
entries = iter(str)
print(next(entries))
print(next(entries))
print(next(entries))
print(next(entries))
print(next(entries))
print(next(entries))
/* Output
I
t
e
r
a
t
*/
mytuple = ("apple", "banana", "cherry")
for x in mytuple:
print(x)
/*Output
apple
banana
cherry
*/
/* ............... END ............... */
Notes:
-
Python Iterator is the object contains a certfain number of values. You can traverse the iterator and get all the values.
- In python we use two function to process iterator , ie. __iter__() and __next__().
- iter() method which is used to get an iterator and next () function is used to print the next entries.
- Python iterator is an object that can be iterated and printe all the values in it.
- You can also use for loop to iterate through an iterable object, please refer program for more information.
- If the iterator object is string array, it will print all strings in array.
- If the iterator contains only one string only, then next will print each character wise.
- Instead of using Iterator you can also use for loop to print all the entries.
Tags
Python iterator next, Python iterator for loop