Skip to content

Merge List Append

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: merge-list-append

Section titled “Sourcery refactoring id: merge-list-append”

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

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

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.