
#Python reminders for people who are keep losing the details. Short code, a plain explanation, one thing worth remembering everyday. @remindmejs
Joined October 2026
- Tweets262
- Following53
- Followers5
- Likes3.3K
from functools import cmp_to_key
nums = ["3", "30", "34", "5"]
k = cmp_to_key(lambda a, b: int(b + a) - int(a + b))
"".join(sorted(nums, key=k)) # "534330"
Python 3 sorted() has no cmp=. Wrap a 2-arg compare (<0 a first, >0 b first) in cmp_to_key().
13
list index() takes start and stop, so you can find the next match:
xs = ["a", "b", "a", "c"]
xs.index("a") # 0
xs.index("a", 1) # 2
xs.index("z") # ValueError
Lists have no find(), so a missing value always raises. Check with in first or catch ValueError.
1
19
p = Point(1, 2)
vars(p) # {'x': 1, 'y': 2}
vars(p)["z"] = 3
p.z # 3
vars(obj) returns the object's own __dict__, not a copy, so edits change the object. Only instance attributes show up, and a class using __slots__ has no __dict__, so vars() raises TypeError.
1
16
(3.0).is_integer() # True
(3.5).is_integer() # False
(0.5).as_integer_ratio() # (1, 2)
(0.1).as_integer_ratio()
# (3602879701896397, 36028797018963968)
as_integer_ratio() shows the exact fraction a float stores, so 0.1 isn't 1/10. is_integer() checks for a whole number.
2
22
Python reminder: bit_length() is how many bits an int needs, sign ignored.
n = 255
n.bit_length() # 8
(256).bit_length() # 9
(-8).bit_length() # 4
(0).bit_length() # 0
Next power of 2 for n >= 1:
1 << (n - 1).bit_length() # 5 -> 8, 8 -> 8
10
Python reminder: yield from hands off to another iterable
def flat(rows):
for row in rows:
yield from row
list(flat([[1, 2], [3]])) # [1, 2, 3]
Same as: for x in row: yield x
Bonus: result = yield from sub() also captures the sub-generator's return value.
9
class Config(dict):
def __missing__(self, key):
return f"<{key}>"
c = Config(a=1)
c["a"] # 1
c["b"] # '<b>'
"b" in c # False
In a dict subclass, __missing__ runs only for c[key]; get() and in skip it. Unlike defaultdict, nothing is stored unless you do it.
8
from collections import OrderedDict
d = OrderedDict(a=1, b=2, c=3)
d.move_to_end("a")
list(d) # ['b', 'c', 'a']
d.popitem(last=False) # ('b', 2)
Plain dicts keep order too, but only OrderedDict moves a key to an end and pops from the front. Handy for a tiny LRU cache.
9
def log(*args, **kwargs):
print(args, kwargs)
log(1, 2, level="hi")
# (1, 2) {'level': 'hi'}
*args collects extra positional arguments into a tuple, **kwargs extra keyword ones into a dict. Names are convention; * and ** do the work. Forward both with f(*args, **kwargs).
7
from datetime import datetime, timezone
a = datetime(2026, 1, 1, 12)
b = datetime(2026, 1, 1, 12, tzinfo=timezone.utc)
a == b # False
a < b # TypeError
No tzinfo means naive, with it means aware. Python won't order a mix: == says False, < raises. Pick one kind.
8
nums = [1, 2, 3]
", ".join(nums)
# TypeError: sequence item 0: expected str instance, int found
", ".join(map(str, nums)) # '1, 2, 3'
join() only accepts strings and never converts for you. Convert first with map(str, ...) or a generator: (str(n) for n in nums).
1
69
len() on a str counts characters, not bytes:
text = "café"
len(text) # 4
len(text.encode()) # 5
In UTF-8 each non-ASCII character takes 2 to 4 bytes. When a DB column, file size or API limit is in bytes, measure the encoded length, not len(text).
11
itertools tee() splits one iterator into independent copies:
from itertools import tee
it = iter([1, 2, 3])
a, b = tee(it)
print(list(a), list(b)) # [1, 2, 3] [1, 2, 3]
After tee(), don't touch it: reading the original makes the copies skip items.
12
from functools import total_ordering
class V:
def __init__(s, n): s.n = n
def __eq__(s, o): return s.n == o.n
def __lt__(s, o): return s.n < o.n
V = total_ordering(V)
V(1) >= V(2) # False
total_ordering adds <=, >, >= from __eq__ plus __lt__. Usually a decorator.
8
nums = [1, 2, 3]
print([1, 2] in nums, "12" in "123", [1, 2] in [[1, 2], 3])
What does this print?
8