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)))
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))
Michael
Ryan
Karin
And the empty case?
values = []
print(next(iter(values)))
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))
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]
About the author
I'm currently working on short form content at ClickHouse. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.