Python Gotcha

copy()

Copy() only do a shallow copy. So if you have a 2D list, it doesn't work:

a = [[1], [2], [3]]
a_copy = a.copy()

for subset in a_copy:
  subset.append(0) # NOTE: this still modifying `a`

a_copy.append("ook")

print(a)
print(a_copy)
[[1, 0], [2, 0], [3, 0]]  # a
[[1, 0], [2, 0], [3, 0], 'ook'] # a_copy

Max key / value of dictionary

[!danger]
Note that you cannot do max(dictionary) since max(dictionary) will return the max key alphabetically

max key:

max(dictionary, key=lambda x: dictionary[x]) # Return the max key

max values

max(dictionary.values())

round, floor and ciel

  • round() will round up if it's >= .5 else it will round down
  • ciel() will always round up
  • floor() will always round down

Defaultdict doesn't work with .get()

from collections import defaultdict
a = defaultdict(lambda: 1)
print(a.get(2)) # None
print(a[2]) # 1