· python til

Python: All about the next function

Yesterday I wrote a blog post about some different ways to take the first element from a Python list. Afterward I was chatting to my new rubber duck, ChatGPT, which suggested the next function on an iterator as an alternative approach. And so that’s what we’re going to explore in this blog post.

The next function gets the first value from an iterator and optionally returns a provided default value if the iterator is empty. Let’s try it out on our example:

values = ["Michael", "Ryan", "Karin", "Mark", "Jennifer", "Will"]
print(next(iter(values)))
Output
Michael

That works well. We could extract the other values as well if we wanted:

values = iter(["Michael", "Ryan", "Karin", "Mark", "Jennifer", "Will"])
print(next(values))
print(next(values))
print(next(values))
Output
Michael
Ryan
Karin

And the empty case?

values = []
print(next(iter(values)))
Output
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

The StopIteration exception gets thrown if you try to read from an iterator that’s been exhausted. We created an empty iterator, so that was to be expected.

Let’s instead pass in a default value:

values = []
print(next(iter(values), None))
Output
None

This time it returns the default value instead of throwing the exception and I think this is probably a nicer solution than the one we ended up with in the last blog post, which was as follows:

values = []
first, *_ = values if len(values) > 0 else [None]
  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket