This built-in is used to create custom looping logic. We can use iter
in a for
-loop. We continue looping while values are returned by iter
.
We usually will call iter
in a for
-loop, as it returns values we can loop over. But sometimes we may call iter
and store the result in a local variable.
With two arguments, iter
continually calls the method passed as argument 1. It stops when the second argument, a value, is reached.
None
element value is reached.import random elements = ["cat", "dog", "horse", None, "gerbil"] def random_element(): # Return random element from list. return random.choice(elements) # Use iter until a None element is returned. for element in iter(random_element, None): print(element)cat horse dog dog gerbil
Here iter
does something different. It acts upon a collection and returns each element in order. This usage is not often needed—we can just reference the collection.
elements = ["cat", "dog", "horse", None, "gerbil"] # Iter returns each element, one after another. for element in iter(elements): print(element)cat dog horse None gerbil
With iter
we get an iterator variable. We must call next()
on this iterator to use it. Here we call next()
to get successive values from a list—no loop is needed.
values = [1, 10, 100, 1000] i = iter(values) # Call the next built-in on an iter. # ... This style of code is not often useful. value = next(i) print(value) value = next(i) print(value) value = next(i) print(value)1 10 100
With iter
we can create custom logic in for
-loops. We can invoke next()
to get the next element from the iterator in a statement.