Python next() Function
next() is a built-in Python function that gets the next element from an iterator.
An iterator is a one-time consumable object;next() it lets us access the elements in an iterator one at a time without loading all the data into memory at once.
Word meaning: next means "next", used to get the next element of an iterator.
Basic syntax and parameters
Syntax format
next(iterator)
next(iterator, default)
Parameter Description
- Parameter iterator:
- Type: iterator
- Description: the iterator from which to get an element.
- Parameter default(optional):
- Type: any value
- Description: the default value returned if the iterator is exhausted.
Function description
- Return Value: returns the next element of the iterator.
- exception: if the iterator is exhausted and no default is specified, a
StopIterationexception.
Example
Example 1: basic usage
Example
Create an iterator from a list
my_list
=
[
1
,
2
,
3
]
iterator
=
iter
(
my_list
)
get the first element
(
next
(
iterator
)
)
Output: 1
Get the second element
(
next
(
iterator
)
)
Output: 2
Get the third element
(
next
(
iterator
)
)
Output: 3
Getting another one raises an exception
print(next(iterator)) # StopIteration
Expected output:
1
2
3
Code analysis:
- First use
iter()Convert an iterable into an iterator. - Each time you call
next()returns one element. - An iterator can only be traversed once and cannot be reset once exhausted.
Example 2: using a default value
Example
Use a default value to avoid the exception
my_list
=
[
1
,
2
]
iterator
=
iter
(
my_list
)
(
next
(
iterator
,
'N/A'
)
)
Output: 1
(
next
(
iterator
,
'N/A'
)
)
Output: 2
(
next
(
iterator
,
'N/A'
)
)
Output: N/A (the iterator is exhausted, the default is returned)
(
next
(
iterator
,
'N/A'
)
)
Output: N/A
Expected output:
1
2
N/A
N/A
Code analysis:
- With a default value specified, an exhausted iterator does not raise an exception.
- This is useful when handling data streams of uncertain length.
Example 3: practical applications
Example
Get elements from a generator
def
fibonacci
(
)
:
a
,
b
=
0
,
1
while
True
:
yield
a
a
,
b
=
b
,
a + b
fib
=
fibonacci
(
)
(
next
(
fib
)
)
Output: 0
(
next
(
fib
)
)
Output: 1
(
next
(
fib
)
)
Output: 1
(
next
(
fib
)
)
Output: 2
(
next
(
fib
)
)
Output: 3
Read the first few lines of a file
with
open
(
"example.txt"
,
"w"
)
as
f:
f.
write
(
"line1\nline2\nline3\n"
)
with
open
(
"example.txt"
)
as
f:
(
next
(
f
)
.
strip
(
)
)
Output: line1
(
next
(
f
)
.
strip
(
)
)
Output: line2
Expected output:
0
1
1
2
3
line1
line2
next() Very useful in scenarios involving generators, streaming data, files, and so on.
Python3 built-in function