Introduction
The next() function in Python will print out the next item of the loop. It will run until the last element of the variable.
It will return items one by one and you can add a default return value if it reaches the last element.
And we will show you how to use the next() function in Python as you go through it below. Hope you understand.
Example
list = iter(["cat", "dog", "tiger"]) x = next(list) print(x) x = next(list) print(x) x = next(list) print(x)
Output:
cat
dog
tiger
Definition
This function prints out the next item of the iterator.
You can add a default return value if it reaches the last element.
This function helps to separate elements clearly.
The syntax
next(iterable, default)
Parameter Values:
iterable: object (Required)
default: default value you add (Optional)
More examples
Example 1: add the default value
list = iter(["cat", "dog", "tiger"]) x = next(list) print(x) x = next(list) print(x) x = next(list) print(x) x = next(list, "pig") print(x)
Output:
cat
dog
tiger
pig
Example 2: Error case
list = iter(["steak", "pizza"]) x = next(list) print(x) x = next(list) print(x) x = next(list) print(x)
Output:
steak
pizza
—————————————————————————
StopIteration Traceback (most recent call last)
Untitled-1 in
4 x = next(list)
5 print(x)
—-> 6 x = next(list)
7 print(x)
StopIteration:
Because the iterator has 2 values but you use the next() function 3 times.
Conclusion
Hope you understood the tutorial on how to use the next() function in Python.
Thanks for reading!