A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://realpython.com/ref/builtin-functions/next/ below:

Python’s Built-in Functions – Real Python

The built-in next() function retrieves the next item from an iterator, raising a StopIteration exception when the iterator is exhausted:

It can also return a default value if the iterator is exhausted, preventing a StopIteration exception:

next() Signature Arguments Argument Description iterator The iterator from which to retrieve the next item. default The value to return if the iterator is exhausted, preventing the StopIteration exception. Return Value next() Examples

With an iterator as an argument:

With a default value:

next() Common Use Cases

The most common use cases for the next() function include:

next() Real-World Example

A typical use case for next() is reading a CSV file and skipping the header line:

In this example, next(file) skips the first line of the file, which contains the headers. This allows the for loop to process only the data lines.

next() in Custom Classes

You can support next() in your custom classes by implementing the .__next__() method. Say that you want to write an iterator that takes a sequence of numbers, computes the square value of each number, and yields those values on demand. In this case, you can write the following class:

This class takes a sequence of numbers as an argument and makes an iterator of square values. The .__next__() method processes the current number and returns its square value. When there are no more items, .__next__() raises the StopIteration exception.

For additional information on related topics, take a look at the following resources:


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4