Skip to content

Merge List Append

Sourcery refactoring id: merge-list-append

Description:

Create the list with values instead of creating an empty list and appending to it

Before:

hats_i_own = []
hats_i_own.append("panama")
hats_i_own.append("baseball_cap")
hats_i_own.append("bowler")

After:

hats_i_own = ["panama", "baseball_cap", "bowler"]

Explanation:

When declaring a list and filling it up with values one way that can come naturally is to declare it as empty and then append to it.

This can be done in place, shortening the code and making the intent more explicit. Now I just need to glance at one line to see that I'm filling a variable with hats, rather than four.

Doing it this way is also slightly more performant since it avoids the function calls to append. The same holds true for filling up other collection types like sets and dictionaries.