Skip to content
Related Articles

Related Articles

Improve Article
Python next() method
  • Last Updated : 04 Dec, 2020

There are many ways to iterate over in Python. next() method also performs the similar task over the iterator. It can be the alternative to iteration in case length is not specified and inbuilt function is not allowed to use.

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.

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

Code #1 : Demonstrating the working of next()






# Python code to demonstrate
# working of next()
  
# initializing list
list1 = [1, 2, 3, 4, 5]
  
# converting list to iterator
list1 = iter(list1)
  
print ("The contents of list are : ")
  
# printing using next()
# using default
while (1) :
    val = next(list1,'end')
    if val == 'end':
        print ('list end')
        break
    else :
        print (val)

Output:

The contents of list are : 
1
2
3
4
5
list end

 
Code #2 : Performance Analysis




# Python code to demonstrate
# next() vs for loop
import time
  
# initializing list
list1 = [1, 2, 3, 4, 5]
  
# keeping list2
list2 = list1
  
# converting list to iterator
list1 = iter(list1)
  
print ("The contents of list are : ")
  
# printing using next()
# using default
start_next = time.time()
while (1) :
    val = next(list1,'end')
    if val == 'end':
        break
    else :
        print (val)
print ("Time taken for next() is : " + str(time.time() - start_next))
  
# printing using for loop
start_for = time.time()
for i in list2 :
    print (i)
print ("Time taken for loop is : " + str(time.time() - start_for))

Output:

The contents of list are : 
1
2
3
4
5
Time taken for next() is : 5.96046447754e-06
1
2
3
4
5
Time taken for loop is : 1.90734863281e-06

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

Applications : next() is the utility function for printing the components of container of iter type. Its usage is when size of container is not known or we need to give a prompt when the list/iterator has exhausted.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :