Notes

`next()` Function in Python [ English ]

< Prev Next >

1. Introduction

The next() function in Python is a built-in function used to retrieve the next item from an iterator. Iterators are objects that allow sequential access to elements of a collection such as a list, tuple, or string.

When next() is called, it returns the next value from the iterator. If there are no more elements left, Python raises a StopIteration exception.

The next() function is commonly used together with the iter() function, which creates an iterator from an iterable object.

2. Syntax

next(iterator, default)

Parameters

  1. iterator An iterator object from which the next element will be returned.

  2. default (optional) A value that will be returned if the iterator has no more elements. If this parameter is not provided and the iterator is exhausted, Python raises a StopIteration error.

Return Value

3. Basic Example

numbers = [10, 20, 30]

it = iter(numbers)

print(next(it))
print(next(it))
print(next(it))

Output

10
20
30

Explanation

4. Example Showing StopIteration

numbers = [1, 2]

it = iter(numbers)

print(next(it))
print(next(it))
print(next(it))

Output

1
2
StopIteration

Explanation

5. Using next() with a Default Value

numbers = [1, 2]

it = iter(numbers)

print(next(it))
print(next(it))
print(next(it, "No more elements"))

Output

1
2
No more elements

Explanation

6. Example with a String

text = "ABC"

it = iter(text)

print(next(it))
print(next(it))
print(next(it))

Output

A
B
C

Explanation

7. Example with a Loop

numbers = [5, 10, 15]

it = iter(numbers)

while True:
    try:
        print(next(it))
    except StopIteration:
        break

Output

5
10
15

Explanation

8. Relationship Between iter() and next()

Function Purpose
iter() Creates an iterator from an iterable
next() Retrieves the next element from the iterator

Example:

numbers = [1, 2, 3]

it = iter(numbers)

print(next(it))

Here:

9. Summary

< Prev Next >