Skip to content
๐Ÿงช Initializing Empty Variables

๐Ÿงช 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

TypeLiteral SyntaxFunction SyntaxNotes
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โœ… comprehensionAvoid 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