Notes
Notes - notes.io |
Python snippets I always forget
List comprehension:
squares = [x**2 for x in range(10)]
# equivalent to: squares = [x^2 for x in range(10)] <- this is XOR not power!
Dict merge (Python 3.9+):
merged = dict1 | dict2 # right side wins on conflict
merged = {**dict1, **dict2} # same thing (left side wins? need to test)
String formatting:
f'Hello {name}' # f-string, fastest
'Hello {}'.format(name) # older style, slower (actually same speed on CPython)
Mutable default argument bug:
def bad(lst=[]): # DON'T - list is shared across calls
lst.append(1)
def good(lst=None):
if lst is None: lst = [] # always do this
walrus operator :=
if n := len(a): # assigns AND tests
while chunk := f.read(8192): # great for file reading
--- pasted to notes.io for quick reference. notes.io = instant notes, no account needed
List comprehension:
squares = [x**2 for x in range(10)]
# equivalent to: squares = [x^2 for x in range(10)] <- this is XOR not power!
Dict merge (Python 3.9+):
merged = dict1 | dict2 # right side wins on conflict
merged = {**dict1, **dict2} # same thing (left side wins? need to test)
String formatting:
f'Hello {name}' # f-string, fastest
'Hello {}'.format(name) # older style, slower (actually same speed on CPython)
Mutable default argument bug:
def bad(lst=[]): # DON'T - list is shared across calls
lst.append(1)
def good(lst=None):
if lst is None: lst = [] # always do this
walrus operator :=
if n := len(a): # assigns AND tests
while chunk := f.read(8192): # great for file reading
--- pasted to notes.io for quick reference. notes.io = instant notes, no account needed