Python Cheat Sheet

Syntax, strings, lists, dicts and common built-ins on one page.

This is the page I wish I'd had pinned next to my screen in my first few months of Python. It isn't the whole language. It's the 20% you'll type every single day: string handling, lists, dictionaries and reading files.

If you're completely new, start with the Python track in Learn and come back here once the basics make sense. If you already write Python and keep looking up the same few things, print this and stick it on the wall.

Strings

s = "BeeProton AI"
s.lower(), s.upper(), s.title(), s.split(), s.replace("AI", "Labs")
f"{price:,.2f}"      # 1,234.50
s[::-1]              # reverse

Lists

nums = [3, 1, 2]
nums.append(4); nums.sort(); nums.pop(); nums.index(2)
sorted(nums, reverse=True); sum(nums); max(nums)
[x * 2 for x in nums if x > 1]

Dicts

d = {"a": 1}
d.get("b", 0); d.items(); d.keys(); d.update(b=2)
{k: v for k, v in d.items() if v > 1}

Useful built-ins

enumerate, zip, range, map, filter, any, all, sorted, reversed, isinstance

Files

with open("data.txt", encoding="utf-8") as f:
    for line in f: ...

Things that trip people up

Strings can't be changed in place. s.upper() gives you a new string; s stays the same. Write s = s.upper() if you want to keep it. Lists are the opposite: nums.sort() changes the list and returns None, so nums = nums.sort() wipes your list out. Use sorted(nums) when you want a new one.

d["key"] vs d.get("key"). Square brackets raise a KeyError if the key is missing. .get() returns None, or a default you pass in. When reading data from forms or APIs, .get() saves a lot of crashes.

Always pass encoding="utf-8" when opening text files. On Windows, Python's default encoding is often not UTF-8, and any Hindi, Tamil or even a rupee symbol (₹) in the file will turn into gibberish or throw an error.

The f-string number formats are worth memorising. f"{x:,.2f}" gives 1,234.50. f"{x:.1%}" turns 0.256 into 25.6%. f"{n:05d}" pads 42 to 00042, handy for invoice numbers.

List comprehensions are for building lists, not for running code. [print(x) for x in items] works, but it builds a useless list of Nones. Use a normal for loop when you just want to do something.

Built-ins worth knowing properly

  • enumerate(items, start=1) gives you a counter without a separate variable.
  • zip(names, marks) walks two lists together; it stops at the shorter one.
  • any() / all() answer "is at least one / is every item true?" without writing a loop.
  • sorted(people, key=lambda p: p["age"]) sorts by any field you like.