DEV Community

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

Posted on

6 3

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay