Python next() explained, with examples

Einblick Content Team - April 14th, 2023

When working with iterable objects in Python, like lists, sets, and tuples, it can be helpful to iterate through the items in the object. One way to do this is by creating an iterator from the iterable, and then using the next() function. In this post, we’ll go through an example using Python next() and the basic syntax.

Basic Syntax: next(iterator, default)

The only argument necessary is an iterator object, which can be created using the iter() function on something like a list, set or tuple. The default argument is optional, and if used, is the message that will pop up once you run out of items in the iterator.

Note: the next() function does not take keyword arguments, so you cannot pass the arguments via their parameter names, just pass the values without naming them. See the example below:

next(iterator, "Out of items")

Python next() Example: Fibonacci sequence

Create an iterator object

# Define a list and a set
lst1 = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

set1 = set(lst1)

# Conver the list and set into iterators
iterator1 = iter(lst1)

iterator2 = iter(set1)


<class 'list'>
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
<class 'set'>
{0, 1, 2, 3, 34, 5, 8, 13, 21}
<class 'list_iterator'>
<class 'set_iterator'>

From the output we can see that Python has detected what the base object was that makes up the iterator.

Call the next() function

In this next code chunk, we defined a function called get3(iterator) which prints the next 3 items from a given iterator. The default value will be "Out of items."

def get3(iterator):
    # Get next item in iterator 1
    item1 = next(iterator, "Out of items")
    item2 = next(iterator, "Out of items")
    item3 = next(iterator, "Out of items")

    print(f'{item1}, {item2}, {item3}')




0, 1, 1
0, 1, 2
2, 3, 5
3, 34, 5
8, 13, 21
34, Out of items, Out of items

From the output, we can see that every subsequent call of the next() function looks at the following item in the iterator, and once the iterator has been exhausted, it prints the default message provided.


Einblick is an agile data science platform that provides data scientists with a collaborative workflow to swiftly explore data, build predictive models, and deploy data apps. Founded in 2020, Einblick was developed based on six years of research at MIT and Brown University. Einblick customers include Cisco, DARPA, Fuji, NetApp and USDA. Einblick is funded by Amplify Partners, Flybridge, Samsung Next, Dell Technologies Capital, and Intel Capital. For more information, please visit and follow us on LinkedIn and Twitter.

Start using Einblick

Pull all your data sources together, and build actionable insights on a single unified platform.

  • All connectors
  • Unlimited teammates
  • All operators