This rule raises an issue when code uses list(iterable)[0] to retrieve the first element of an iterable.

Why is this an issue?

Using list(iterable)[0] to get the first element of an iterable is inefficient because it materializes the entire iterable into a list in memory before accessing the first element.

This approach has two main problems:

The pattern is particularly problematic with:

What is the potential impact?

How to fix it

Replace list(iterable)[0] with next(iter(iterable)) to retrieve only the first element without materializing the entire iterable into a list. The iter() function creates an iterator, and next() retrieves the next item from that iterator, in O(1) time and without allocating memory for the entire collection.

Note that the two expressions differ in the exception raised when the iterable is empty: list(iterable)[0] raises IndexError, while next(iter(iterable)) raises StopIteration. If the surrounding code catches IndexError, update the handler after applying this fix.

Code examples

Noncompliant code example

def get_first_user(users):
    return list(users)[0]  # Noncompliant

Compliant solution

def get_first_user(users):
    return next(iter(users))

Resources

Documentation

External coding guidelines