Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python next() Function

Python next() Function

Python3 Built-in Functions Python3 built-in 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

- Type: iterator - Description: the iterator from which to get an element. - Type: any value - Description: the default value returned if the iterator is exhausted.

Function description


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

print

(

next

(

iterator

)

)

 

Output: 1

Get the second element

print

(

next

(

iterator

)

)

 

Output: 2

Get the third element

print

(

next

(

iterator

)

)

 

Output: 3

Getting another one raises an exception

print(next(iterator))  # StopIteration

Expected output:

1
2
3

Code analysis:

  1. First use iter() Convert an iterable into an iterator.
  2. Each time you call next() returns one element.
  3. 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

)

print

(

next

(

iterator

,

'N/A'

)

)

 

Output: 1

print

(

next

(

iterator

,

'N/A'

)

)

 

Output: 2

print

(

next

(

iterator

,

'N/A'

)

)

 

Output: N/A (the iterator is exhausted, the default is returned)

print

(

next

(

iterator

,

'N/A'

)

)

 

Output: N/A

Expected output:

1
2
N/A
N/A

Code analysis:

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

(

)

print

(

next

(

fib

)

)

 

Output: 0

print

(

next

(

fib

)

)

 

Output: 1

print

(

next

(

fib

)

)

 

Output: 1

print

(

next

(

fib

)

)

 

Output: 2

print

(

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:

   

print

(

next

(

f

)

.

strip

(

)

)

 

Output: line1

   

print

(

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 Functions Python3 built-in function