Open In App

Python next() method

Improve
Improve
Like Article
Like
Save
Share
Report

Python’s next() function returns the next item of an iterator.

Example 

Let us see a few examples to see how the next() method in Python works.

Python3




l = [1, 2, 3]
l_iter = iter(l) 
print(next(l_iter))


Output

1

Note:

The .next() method was a method for iterating over a sequence in Python 2.  It has been replaced in Python 3 with the next() function, which is called using the built-in next() function rather than a method of the sequence object.

Python next() Method Syntax

The next() method in Python has the following syntax:

Syntax : next(iter, stopdef)

Parameters : 

  • iter : The iterator over which iteration is to be performed.
  • stopdef : Default value to be printed if we reach end of iterator.

Return : Returns next element from the list, if not present prints the default value. If default value is not present, raises the StopIteration error.

Python next() Method Examples

Iterating a List using the next() Function

Here we will see the next() in a Python loop. next(l_iter, “end”) will return “end” instead of raising the StopIteration error when iteration is complete.

Python3




# define a list
l = [1, 2, 3
# create list_iterator
l_iter = iter(l) 
 
while True:
    # item will be "end" if iteration is complete
    item = next(l_iter, "end")
    if item == "end":
        break
    print(item)


Output

1
2
3

Get the next item from the iterator

In this example, we take a Python list and use the next() function on it. When for the first time the next() function is called, it returns the first element from the iterator list. When the second time the next() function is called, it returns the second element of the list.

Python3




list1 = [1, 2, 3, 4, 5]
 
# converting list to iterator
l_iter = iter(list1)
 
print("First item in List:", next(l_iter))
print("Second item in List:", next(l_iter))


Output

First item in List: 1
Second item in List: 2

Passing default value to next()

Here we have passed “No more element” in the 2nd parameter of the next() function so that this default value is returned instead of raising the StopIteration error when the iterator is exhausted.

Python3




list1 = [1]
 
# converting list to iterator
list_iter = iter(list1)
 
print(next(list_iter))
print(next(list_iter, "No more element"))


Output

1
No more element

Python next() StopIteration

In this example, when the next function is called beyond the size of the list, that is for the third time, it raised a ‘StopIteration” exception which indicates that there are no more items in the list to be iterated.

Python3




l_iter = iter([1, 2])
 
print("Next Item:", next(l_iter))
print("Next Item:", next(l_iter))
 
# this line should raise StopIteration exception
print("Next Item:", next(l_iter))


Output:

Next Item: 1
Next Item: 2

---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
Input In [69], in <cell line: 6>()
      4 print("Next Item:", next(l_iter))
      5 # this line should raise StopIteration exception
----> 6 print("Next Item:", next(l_iter))

StopIteration: 

While calling out of the range of the iterator then it raises the Stopiteration error, to avoid this error we will use the default value as an argument.

Performance Analysis

This example demonstrates two approaches to iterating a list in Python. One is using the next method and the other is by using a for loop and comparing them with each other to see which method performs better and in less time.

Python3




import time
 
# initializing list
l = [1, 2, 3, 4, 5]
 
# Creating iterator from list
l_iter = iter(l)
 
print("[Using next()]The contents of list are:")
 
# Iterating using next()
start_next = time.time_ns()
while (1):
    val = next(l_iter, 'end')
    if val == 'end':
        break
    else:
        print(val, end=" ")
 
print(f"\nTime taken when using next()\
is : {(time.time_ns() - start_next) / 10**6:.02f}ms")
 
# Iterating using for-loop
print("\n[Using For-Loop] The contents of list are:")
start_for = time.time_ns()
for i in l:
    print(i, end=" ")
print(f"\nTime taken when using for loop is\
: {(time.time_ns() - start_for) / 10**6:.02f}ms")


Output

[Using next()]The contents of list are:
1 2 3 4 5 
Time taken when using next()is : 0.02ms

[Using For-Loop] The contents of list are:
1 2 3 4 5 
Time taken when using for loop is: 0.01ms

Conclusion: Python For loop is a better choice when printing the contents of the list than next().

Applications: next() is the Python built-in function for iterating the components of a container of an iterator type. Its usage is when the size of the container is not known, or we need to give a prompt when the iterator has exhausted (completed).



Last Updated : 19 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads