Skip to content
Related Articles

Related Articles

Python next() method

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 03 Aug, 2022
Improve Article
Save Article

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

Python next() method 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 Example

Python3




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

Output:

1

Example 1: Iterating a list using next() function

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

Python3




l = [1, 2, 3# define a list
l_iter = iter(l)  # create list_iterator
 
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

Example 2: Get the next item from the iterator

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

Example 3: 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

Example 4: Python next() StopIteration

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 iterator then it raises the Stopiteration error, to avoid this error we will use the default value as an argument.

Example 5: Performance Analysis

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.23ms

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

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 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).


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!