An example of a method to use a python iterator
- 2020-04-02 13:16:38
- OfStack
What is an iterator?
The iterator is a simple object with a next method, and of course implements the function with the next method. Iterators can iterate over a sequence of values, and when no iteration is available, the next method raises a StopIteration exception. Many objects in python are iterators, such as lists, elements, strings, files, maps, and collections
How to use iterators?
1. For variable in iterable object
list1 = [1,2,3,4,5]
for ele in list1:
print ele,
The result is: 1, 2, 3, 4, 5
2. If the variable in can iterate the object
list1 = [1,2,3,4,5]
var = 1
if var in list1:
print 'yes!'
else:
print 'No'
3. Variable = iter(iterable object)
it = iter([1,2,3,4])
print it.next()
print it.next()
print it.next()
The result is:
1
2
3
Finally, to summarize: an iterator is an object