C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Here: We loop over random elements from the list until a None element value is reached.
DefforPython program that uses iter
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)
Output
cat
horse
dog
dog
gerbil
Python program that uses iter, single argument
elements = ["cat", "dog", "horse", None, "gerbil"]
# Iter returns each element, one after another.
for element in iter(elements):
print(element)
Output
cat
dog
horse
None
gerbil
Python program that uses next
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)
Output
1
10
100