next() Function in Python

Python next() Function

The next() function in Python is used to retrieve the next item from an iterator. It takes an iterator object as an argument and returns the next element in the iterator.

Here's the general syntax of the next() function:

next(iterator, default)

The iterator parameter is the iterator object from which you want to fetch the next item. The default parameter is an optional value that you can provide. If the iterator is exhausted and there are no more items to retrieve, the next() function will raise a StopIteration exception. However, if you provide a default value, it will be returned instead of raising an exception.

Here's an example that demonstrates the usage of the next() function:

numbers = iter([1, 2, 3, 4, 5])

print(next(numbers))  # Output: 1
print(next(numbers))  # Output: 2
print(next(numbers))  # Output: 3

# Using default value
print(next(numbers, 'End'))  # Output: 4
print(next(numbers, 'End'))  # Output: 5
print(next(numbers, 'End'))  # Output: 'End'

In this example, we create an iterator object numbers from a list [1, 2, 3, 4, 5]. We then use the next() function to retrieve each item from the iterator. After fetching all the items, we can see that calling next() beyond the available items will either raise a StopIteration exception or return the provided default value.