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 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
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jul 10, 2024 (edit).