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]
print(type(lst1))
print(lst1)

set1 = set(lst1)
print(type(set1))
print(set1)

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

iterator2 = iter(set1)
print(type(iterator2))

Output:

<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}')

get3(iterator1)
get3(iterator2)
get3(iterator1)
get3(iterator2)

get3(iterator1)
get3(iterator1)

Output:

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.

About

Einblick is an AI-native data science platform that provides data teams with an agile 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 is funded by Amplify Partners, Flybridge, Samsung Next, Dell Technologies Capital, and Intel Capital. For more information, please visit www.einblick.ai 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