Skip to content

[Edit] Python Built-in Functions: next() #7275

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 8, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 69 additions & 29 deletions content/python/concepts/built-in-functions/terms/next/next.md
Original file line number Diff line number Diff line change
@@ -1,33 +1,43 @@
---
Title: 'next()'
Description: 'Returns the next element from an iterable object.'
Description: 'Returns the next element from an iterator object.'
Subjects:
- 'Computer Science'
- 'Data Science'
Tags:
- 'Collections'
- 'Functions'
- 'Methods'
- 'Collections'
- 'Values'
CatalogContent:
- 'learn-python-3'
- 'paths/data-science'
---

The **`next()`** function returns the next element from an [iterator](https://www.codecademy.com/resources/docs/python/iterators) object.
In Python, the **`next()`** function returns the next element from an [iterator](https://www.codecademy.com/resources/docs/python/iterators) object. It is especially useful when:

- Manually iterating through items in a loop
- Working with generators
- Handling potentially infinite sequences or data streams

## Syntax

```pseudo
next(iterator_object, [default_parameter])
next(iterator, default)
```

The `iterator_object` is required. The `default_parameter` is optional and is printed if the end of the iterator is reached.
**Parameters:**

- `iterator`: An object that implements the iterator protocol.
- `default` (Optional): A value returned if the iterator is exhausted. If not provided, `StopIteration` is raised when there are no more items.

**Return value:**

> **Note:** If the next element is missing from the object, the `default_parameter` is returned. Without a set `default_parameter`, a `StopIteration` [error](https://www.codecademy.com/resources/docs/python/errors) is thrown.
Returns the next item from the iterator. If the iterator is exhausted and a `default` is provided, returns the `default`; otherwise, raises `StopIteration`.

## Example
## Example 1: Using `next()` with an Iterator

In this example, a list called `list_items` is converted to an iterable object via the `iter()` function, and each element is printed by means of the `next()` function:
In this example, a list called `list_items` is converted into an iterator object via the `iter()` function, and each element is printed by means of the `next()` function:

```py
list_items = iter(["Hi", 27, "Python", 10])
Expand All @@ -37,7 +47,7 @@ print(next(list_items))
print(next(list_items))
```

This outputs the following:
Here is the output:

```shell
Hi
Expand All @@ -46,32 +56,62 @@ Python
10
```

If one more `print()` runs without the default parameter, an `StopIteration` error will be thrown:

```shell
Traceback (most recent call last):
File "main.py", line 6, in <module>
print(next(list_items))
StopIteration
```

> **Note:** This can also be done with a [`for` loop](https://www.codecademy.com/resources/docs/python/loops). However, the `for` loop actually generates its own iterator object and applies the `next()` function between each element. Since there is no risk of overflowing the list, a default parameter is not needed:
>
> ```py
> list_items = iter(["Hi", 27, "Python", 10])
> for item in list_items:
> print(item)
> ```
## Example 2: Handling `StopIteration` with Default Value

## Codebyte Example
This example iterates over a list with the `next()` function, but prevents the program from crashing with a default parameter:

This example iterates over the same list with the `next()` function, but prevents the program from crashing with a default parameter:

```codebyte/python:
```py
list_items = iter(["Hi", 27, "Python", 10])
print(next(list_items, "That's all folks"))
print(next(list_items, "That's all folks"))
print(next(list_items, "That's all folks"))
print(next(list_items, "That's all folks"))
print(next(list_items, "That's all folks"))
```

Here is the output:

```shell
Hi
27
Python
10
That's all folks
```

## Codebyte Example: Using `next()` with a Generator

This codebyte example uses a generator function that yields numbers in descending order. Here, `next()` is used to manually fetch each value, and the optional default parameter helps avoid exceptions:

```codebyte/python
def countdown(n):
while n > 0:
yield n
n -= 1

counter = countdown(3)

print(next(counter))
print(next(counter))
print(next(counter))
print(next(counter, "Finished"))
```

## Frequently Asked Questions

### 1. What happens if `next()` is called on a non-iterator object?

If you call `next()` on a non-iterator object, you’ll get a `TypeError`. The object must be an iterator, or you can convert an iterable into one using `iter()`.

### 2. What is the difference between `for` loops and `next()`?

`for` loops internally use `next()` but also handle `StopIteration` automatically. Using `next()` gives you manual control over iteration.

### 3. How is `next()` useful with files?

File objects are iterators. You can use `next()` to read one line at a time from a file:

```py
with open('sample.txt') as f:
print(next(f)) # Reads the first line
```