Skip to content

For Append To Extend

Sourcery refactoring id: for-append-to-extend

Description

Replace a for append loop with list extend

Before

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

After

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

Explanation

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.

Was this page helpful?