Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python oct() Function
Next article icon

Python next() method

Last Updated : 19 Jun, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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



Next Article
Python oct() Function
author
manjeet_04
Improve
Article Tags :
  • Python
  • python
  • Python-Built-in-functions
Practice Tags :
  • python
  • python

Similar Reads

  • float() in Python
    Python float() function is used to return a floating-point number from a number or a string representation of a numeric value. Example: Here is a simple example of the Python float() function which takes an integer as the parameter and returns its float value. C/C++ Code # convert integer value to f
    3 min read
  • Python String format() Method
    format() method in Python is a tool used to create formatted strings. By embedding variables or values into placeholders within a template string, we can construct dynamic, well-organized output. It replaces the outdated % formatting method, making string interpolation more readable and efficient. E
    9 min read
  • Python - globals() function
    In Python, the globals() function is used to return the global symbol table - a dictionary representing all the global variables in the current module or script. It provides access to the global variables that are defined in the current scope. This function is particularly useful when you want to in
    2 min read
  • Python hash() method
    Python hash() function is a built-in function and returns the hash value of an object if it has one. The hash value is an integer that is used to quickly compare dictionary keys while looking at a dictionary. Python hash() function SyntaxSyntax : hash(obj) Parameters : obj : The object which we need
    6 min read
  • hex() function in Python
    hex() function in Python is used to convert an integer to its hexadecimal equivalent. It takes an integer as input and returns a string representing the number in hexadecimal format, starting with "0x" to indicate that it's in base-16. Example: [GFGTABS] Python a = 255 res = hex(a) print(res) [/GFGT
    2 min read
  • id() function in Python
    In Python, id() function is a built-in function that returns the unique identifier of an object. The identifier is an integer, which represents the memory address of the object. The id() function is commonly used to check if two variables or objects refer to the same memory location. Python id() Fun
    3 min read
  • Python 3 - input() function
    In Python, we use the input() function to take input from the user. Whatever you enter as input, the input function converts it into a string. If you enter an integer value still input() function converts it into a string. Python input() Function SyntaxSyntax: input(prompt) Parameter: Prompt: (optio
    3 min read
  • Python int() Function
    The Python int() function converts a given object to an integer or converts a decimal (floating-point) number to its integer part by truncating the fractional part. Example: In this example, we passed a string as an argument to the int() function and printed it. [GFGTABS] Python age = "21"
    4 min read
  • Python len() Function
    The len() function in Python is used to get the number of items in an object. It is most commonly used with strings, lists, tuples, dictionaries and other iterable or container types. It returns an integer value representing the length or the number of elements. Example: [GFGTABS] Python s = "G
    2 min read
  • Python map() function
    The map() function is used to apply a given function to every item of an iterable, such as a list or tuple, and returns a map object (which is an iterator). Let's start with a simple example of using map() to convert a list of strings into a list of integers. [GFGTABS] Python s = ['1', '
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences