Iter. 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.
Iter usage. 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.
Example, two arguments. With two arguments, iter continually calls the method passed as argument 1. It stops when the second argument, a value, is reached.
Here We loop over random elements from the list until a 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
Example, one argument. 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
Iter, next method. With iter we get an iterator variable. We must call next() on this iterator to use it. Here I 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
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 25, 2022 (edit).