unnecessary-iterable-allocation-for-first-element (RUF015)#
Fix is always available.
What it does#
Checks for uses of list(...)[0]
that can be replaced with
next(iter(...))
.
Why is this bad?#
Calling list(...)
will create a new list of the entire collection, which
can be very expensive for large collections. If you only need the first
element of the collection, you can use next(...)
or next(iter(...)
to
lazily fetch the first element.
Example#
Use instead:
Fix safety#
This rule's fix is marked as unsafe, as migrating from list(...)[0]
to
next(iter(...))
can change the behavior of your program in two ways:
- First,
list(...)
will eagerly evaluate the entire collection, whilenext(iter(...))
will only evaluate the first element. As such, any side effects that occur during iteration will be delayed. - Second,
list(...)[0]
will raiseIndexError
if the collection is empty, whilenext(iter(...))
will raiseStopIteration
.