Python iter Example: next

This Python example page uses the iter built-in and the next method. Iter is used in for-loops.
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.
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.

DefFor
Python 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
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.
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
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.
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
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.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
HomeSearch
Home
Dot Net Perls