The Wayback Machine - https://web.archive.org/web/20240826020505/https://www.geeksforgeeks.org/python-next-method/
Open In App

Python next() method

Last Updated : 19 Jun, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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



Previous Article
Next Article

Similar Reads

Interesting Python Implementation for Next Greater Elements
Given an array, print the Next Greater Element (NGE) for every element. The Next greater Element for an element x is the first greater element on the right side of x in array. Elements for which no greater element exist, consider next greater element as -1. Examples: Input : 11, 13, 21, 3, 9, 12 Output : 11 --&gt; 21 13 --&gt; 21 21 --&gt; -1 3 --
2 min read
SymPy | Prufer.next() in Python
Prufer.next() : next() is a sympy Python library function that returns the Prufer sequence that is delta beyond the current one. Syntax : sympy.combinatorics.Prufer.prufer.next() Return : Prufer sequence that is delta beyond the current one Code #1 : next() Example # Python code explaining # SymPy.Prufer.next() # importing SymPy libraries from symp
1 min read
Python VLC MediaListPlayer - Playing Next Item
In this article we will see how we can play the next item in the MediaListPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Media list player is used to play multiple media in a row for example playing a serie
3 min read
Class Method vs Static Method vs Instance Method in Python
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
5 min read
Next Sentence Prediction using BERT
Pre-requisite: BERT-GFG BERT stands for Bidirectional Representation for Transformers. It was proposed by researchers at Google Research in 2018. Although, the main aim of that was to improve the understanding of the meaning of queries related to Google Search. A study shows that Google encountered 15% of new queries every day. Therefore, it requir
7 min read
PyQt5 QSpinBox - Getting next widget in focus chain
In this article we will see how we can get the next in focus chain widget of the spin box. Spin box consist of two child widgets one is line edit and other one is the arrow buttons. Focus is set widget by widget i.e focus chain there fore when spin box get focus its one child get focus before the another child. In order to do this we use nextInFocu
2 min read
PyQt5 QCalendarWidget - Showing Next Month
In this article we will see how we can show the next month of the QCalendarWidget to the screen. Showing the next month means the next month relative to the currently displayed month. Note : The selected date is not changed. In order to do this we will use showNextMonth method with the QCalendarWidget object.Syntax : calendar.showNextMonth()Argumen
2 min read
PyQt5 QCalendarWidget - Showing Next Year
In this article we will see how we can show the next year of the QCalendarWidget to the screen. Showing the next year means the next year relative to the currently displayed year. Note : The selected date is not changed. In order to do this we will use showNextYear method with the QCalendarWidget object.Syntax : calendar.showNextYear()Argument : It
2 min read
PyQt5 QCalendarWidget - Making focus to next-previous child
In this article we will see how we can make the focus to any other widget from QCalendarWidget. In order to do this we use focusNextPrevChild method. It finds a new widget to give the keyboard focus to, as appropriate for Tab and Shift+Tab, and returns true if it can find a new widget, or false if it can't. In order to do this we will use focusNext
2 min read
PyQt5 QCalendarWidget - Making focus to next child
In this article we will see how we can make the focus to the next widget from QCalendarWidget. In order to do this we use focusNextChild method. It finds a new widget to give the keyboard focus to, as appropriate for Tab, and returns true if it can find a new widget, or false if it can't. In order to do this we will use focusNextChild method with t
2 min read
PyQt5 QCalendarWidget - Getting next widget in focus chain
In this article we will see how we can get the next widget in the focus chain of QCalendarWidget. Focus chain is the list of widgets/children present in the window, they tell the sequence of focus, first item in the focus chain will receive focus first. In order to do this we will use nextInFocusChain method with the QCalendarWidget object. Syntax
2 min read
PyQt5 QCalendarWidget - Setting Border to the Next Month button for all states
In this article we will see how we can set border to the next month button of the QCalendarWidget. Next month button is on the right hand size in the tool buttons, tool buttons are the buttons available at the top i.e buttons to go to left and right page, setting border to QCalendarWidget is not like setting border to the other widgets, calendar is
2 min read
PyQt5 QCalendarWidget - Background Color of the Next Month button
In this article we will see how we can set background color to the next month button of the QCalendarWidget. Next month button is on the right hand size in the tool buttons, tool buttons are the buttons available at the top i.e buttons to go to left and right page, setting background color to QCalendarWidget is not like setting background color to
2 min read
PyQt5 QCommandLinkButton - Going to next state
In this article we will see how we can go to the next state of the checkable QCommandLinkButton. We can make the command link button checkable with the help of setCheckable method, this will make two states of the command link button which will be checked i.e pressed and unchecked i.e released state. Next state will change the state according to th
2 min read
PYGLET – Step to Next Frame in Player
In this article, we will see how we can step up next frame in media of player of PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia, etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set
3 min read
PYGLET – Play Next Media in Player
In this article we will see how we can play next media which is in queue of player of PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be
3 min read
How to get the next page on BeautifulSoup?
In this article, we are going to see how to Get the next page on beautifulsoup. Modules NeededBeautifulSoup: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. To install this module type the below command in the terminal.pip install bs4requests: This library allows you to send HTTP/1.1 requests extremely easily. To
4 min read
Next Word Prediction with Deep Learning in NLP
Identifying the most likely word to follow a given string of words is the basic goal of the Natural Language Processing (NLP) task of "next word prediction." This predictive skill is essential in various applications, including text auto-completion, speech recognition, and machine translation. Deep learning approaches have transformed NLP by attain
9 min read
Difference between Method Overloading and Method Overriding in Python
Method Overloading: Method Overloading is an example of Compile time polymorphism. In this, more than one method of the same class shares the same method name having different signatures. Method overloading is used to add more to the behavior of methods and there is no need of more than one class for method overloading.Note: Python does not support
3 min read
Class method vs Static method in Python
In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python. What is Class Method in Python? The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated after your function is defined. The result of that
5 min read
Pandas DataFrame iterrows() Method | Pandas Method
Pandas DataFrame iterrows() iterates over a Pandas DataFrame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in the form of a series. Example: Python Code import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 32, 3
2 min read
Pandas DataFrame interpolate() Method | Pandas Method
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Python Pandas interpolate() method is used to fill NaN values in the DataFrame or Series using various interpolation techniques to fill the m
3 min read
Pandas DataFrame duplicated() Method | Pandas Method
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas duplicated() method identifies duplicated rows in a DataFrame. It returns a boolean series which is True only for unique rows. Ex
3 min read
What is the Proper Way to Call a Parent's Class Method Inside a Class Method?
In object-oriented programming, calling a parent class method inside a class method is a common practice, especially when you want to extend or modify the functionality of an inherited method. This process is known as method overriding. Here's how to properly call a parent class method inside a class method in Python. Basic Syntax Using super()The
3 min read
Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 min read
Python | os._exit() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os._exit() method in Python is used to exit the process with specified status without calling cleanup handlers, flushing stdio buff
2 min read
Python | os.WEXITSTATUS() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.WEXITSTATUS() method in Python is used to get the integer parameter used by a process in exit(2) system call if os.WIFEXITED(sta
3 min read
Python | os.abort() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.abort() method in Python is used to generate a SIGABRT signal to the current process. On Unix, this method produces a core dump
2 min read
Python | os.renames() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.renames() method is a recursive directory or file renaming function. It works like os.rename() method except creation of any int
2 min read
Python | os.lseek() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.lseek() method sets the current position of file descriptor fd to the given position pos which is modified by how. Syntax: os.ls
3 min read
Practice Tags :