Python | next () method

Python Methods and Functions

There are many ways to iterate over in Python. The next() method also performs a similar task through an iterator. This can be an alternative to iteration if no length is specified and the inline function is not allowed.

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: Demo next ()

# Python code for demo
# working next ()

 
# initializing list

list1 = [ 1 , 2 , 3 , 4 , 5 ]

 
# convert list to iterator

list1 = iter (list1)

 

print ( "The contents of list are:" )

  
# print using next ()
# 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 for demo
# next () versus loop

import time

 
# initializing list

list1 = [ 1 , 2 , 3 , 4 , 5 ]

 
# keep list2

list2 = list1

 
# convert list to iterator

list1 = iter (l ist1)

 

print ( "The contents of list are:" )

 
# printing using next ()
# using software 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 ))

 
# print using a for loop

start_for = time.time ()

for i in list2:

print (i)

print ( " Time taken for loop is: " + str (time.time () - start_for))

Exit:

 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 a better choice than next () when printing list contents.

Applications: next () — it is a utility function for printing container components of type iter. It is used when the size of the container is unknown, or we need to give a hint when the list / iterator is exhausted.





Tutorials