Python next() method
Python next() function returns the next item of an iterator.
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
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)) |
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 listl_iter = iter(l) # create list_iteratorwhile True: # item will be "end" if iteration is complete item = next(l_iter, "end") if item == "end": break print(item) |
1 2 3
Example 2: Get the next item from the iterator
Python3
list1 = [1, 2, 3, 4, 5]# converting list to iteratorl_iter = iter(list1)print("First item in List:", next(l_iter))print("Second item in List:", next(l_iter)) |
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 iteratorlist_iter = iter(list1)print(next(list_iter))print(next(list_iter, "No more element")) |
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 exceptionprint("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 listl = [1, 2, 3, 4, 5]# Creating iterator from listl_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-loopprint("\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") |
[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 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).


Please Login to comment...