Python next() function
Instance
Create an iterator and print items one by one:
mylist = iter(["apple", "banana", "cherry"]) x = next(mylist) print(x) x = next(mylist) print(x) x = next(mylist) print(x)
Definition and Usage
The next() function returns the next item in the iterator.
You can add a default return value to return when iteration ends.
Syntax
next(iterable, default)
Parameter Value
Parameter | Description |
---|---|
iterable | Required. An iterable object. |
default | Optional. The default value returned when iteration ends. |
More Instances
Instance
Return a default value when iteration ends:
mylist = iter(["apple", "banana", "cherry"]) x = next(mylist, "orange") print(x) x = next(mylist, "orange") print(x) x = next(mylist, "orange") print(x) x = next(mylist, "orange") print(x)