Skip to content

For Append To Extend

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.

Back to top