๐งช Initializing Empty Variables
โ Preferred Syntax
empty_list = [] # Fastest, most readable
empty_tuple = () # Literal syntax, no ambiguity
empty_dict = {} # Clean and idiomatic
empty_set = set() # Required โ {} creates a dict๐ฆ Pre-filled Dictionary (Scalable Initialization)
keys = ['a', 'b', 'c']
pre_filled_dict = dict.fromkeys(keys, None) # All keys map to Noneโ ๏ธ Mutable Default Pitfall
# โ All keys share the same list reference
bad_dict = dict.fromkeys(keys, [])
# โ
Each key gets its own list
good_dict = {key: [] for key in keys}๐ง Semantic Audit Flags
| Type | Literal Syntax | Function Syntax | Notes |
|---|---|---|---|
| List | [] | list() | Prefer [] for speed/readability |
| Tuple | () | tuple() | Prefer () unless dynamic |
| Set | โ {} | โ
set() | {} creates a dict |
| Dict | โ
{} | dict() | Both fine; {} preferred |
| Pre-fill | โ shared refs | โ comprehension | Avoid shared mutable defaults |
๐งญ Motivation
- Literal syntax is faster and more idiomatic.
- Function calls are useful for dynamic or explicit initialization.
- Audit clarity matters when defaults are mutable or reused.
# Audit-safe initialization
flags = {key: False for key in keys}
buffers = {key: [] for key in keys}Last updated on