Skip to content

Merge Set Add

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.

Create the set with values instead of declaring an empty set and adding to it

hats_i_own = set()
hats_i_own.add("panama")
hats_i_own.add("baseball_cap")
hats_i_own.add("bowler")
hats_i_own = {"panama", "baseball_cap", "bowler"}

When declaring a set and filling it up with values one way that can come naturally is to declare it as empty and then add 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 add. The same holds true for filling up other collection types like lists and dictionaries.