In Python, an iterable is any object you can iterate. It can be a list, a sequence and other types of collections.
If you have an iterable, you can pass it in iter()
and use next()
to iterate over it. It will return a new element of the iterable each time you call the next()
function.
The example below creates an iterable (a list) that we then loop over using both an iterator and a for loop.
# creating a list
new_list = [1, 2, 3, 4, 5]
# using iter()
new_iter = iter(new_list)
# print 1
print(next(new_iter))
# print 2
print(next(new_iter))
# print 3
print(new_iter.__next__())
# print 7
print(new_iter.__next__())
# print 9
print(new_iter.__next__())
# looping thru new_list with a for loop
for element in new_list:
print(element)
This would output:
1
2
3
4
5
1
2
3
4
5
So you can use both a for loop or an iterator to go over an object.
To use iter()
the object must be an iterable and not a single value like an integer.
If there is no new item, it will throw an StopException:
>>> s = ['Tea','Milk','Water']
>>> itb = iter(s)
>>> next(itb)
'Tea'
>>> next(itb)
'Milk'
>>> next(itb)
'Water'
>>> next(itb)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
Top comments (0)