Skip to content

For Append To Extend

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

Sourcery refactoring id: for-append-to-extend

Section titled “Sourcery refactoring id: for-append-to-extend”

Replace a for append loop with list extend

games = []
for i in range(10):
for j in range(10):
if i != j:
games.append(play(i, j))
games = []
for i in range(10):
games.extend(play(i, j) for j in range(10) if i != j)

Instead of looping through an iterator and appending to the list, we can make the intent clearer by explicitly stating that we are extending this list.