DEV Community

Cover image for The next() Function Explained
Mangabo Kolawole
Mangabo Kolawole

Posted on

The next() Function Explained

The next() function returns the next item of an iterator. It's used to iterate over an iterator in the required manner.

It takes two arguments:

  • the iterator
  • And the default value if the iterable has reached its end

Here's an example

>>> new_fruits = iter(['lemon is a fruit.', 'orange is a fruit.', 'banana is a fruit.'])
>>> next(new_fruits)
'lemon is a fruit.'
>>> next(new_fruits)
'orange is a fruit.'
>>> next(new_fruits)
'banana is a fruit.'
>>> next(new_fruits)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
Enter fullscreen mode Exit fullscreen mode

If the second value is not passed to the next function, it'll simply return a StopIteration error.

Let's also see how we can write a while loop using next().

>>> fruits = iter(["lemon", "orange", "banana"])
>>> while True:
...     next_value = next(fruits, "end")
...     if next_value == "end":
...             break
...     else:
...             print(next_value)
... 
lemon
orange
banana
Enter fullscreen mode Exit fullscreen mode

Why use next() over for loop? Well, the next() function definitely takes much more time compared to loops, however, if you want certainty about what's happening in each step, it's the right tool to use.

Article posted using bloggu.io. Try it for free.

Top comments (0)