Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python3
python
communitycreator

What is the next() function in Python?

Maria Elijah

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

In Python, the next() function returns the next item from an iterator.

Syntax

next(iterator, default)

Parameters

  • iterator: This represents the iterable. It is required.
  • qdefault: This represents the value used when the iterable has reached its end. It is optional.

Return value

This function returns the next item from an iterable.

Example

# create list
basket = ["Apple", "Pawpaw","Orange","Banna","Grapes","lemon","Pea"]
# using iter() to convert the list to an iterator
basket_iterator = iter(basket)
print(basket_iterator)
# display the next value from the iterator
print(next(basket_iterator))
# display the next value from the iterator
print(next(basket_iterator))

Explanation

  • Line 3: We create a list called basket.
  • Line 5–6: We convert the list to an iterator using the iter() function and assign it to a variable called basket_iterator.
  • Line 6: Next, we display the memory location of the iterator.
  • Line 10: We display the next value from the basket_iterator using the next() function.
  • Line 13: We display the next value from the basket_iterator using the next() function.

Note: The StopIteration exception is thrown if the default parameter is omitted and the iterator has reached its end.

RELATED TAGS

python3
python
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring