Python Central HubSign in

Guides

Python Cheat Sheet

A compact Python cheat sheet covering syntax, strings, lists, dicts, sets, comprehensions, functions, classes, files, exceptions and the standard library.

What you'll learn

  • The Python syntax and built-in types you reach for every day
  • Compact tables for strings, lists, dicts and sets
  • Comprehensions, functions, classes, files and exceptions at a glance
  • A short tour of the most useful standard library modules

Keep this page open while you code. Each section is a reminder, not a full lesson. Follow the course lessons for the explanations.

Syntax basics

IdeaExample
Comment# a comment
Variableage = 30
Multiple assigna, b = 1, 2
Swapa, b = b, a
Typesint, float, str, bool, list, tuple, dict, set, None
Check typetype(x), isinstance(x, int)
Convertint("5"), float("1.5"), str(10), list("abc")
Arithmetic+ - * / // % **
Compare== != < > <= >=
Logicand, or, not
Membershipx in items, x not in items
Python
x = 7
if x > 10:
    print("big")
elif x > 5:
    print("medium")
else:
    print("small")
 
for i in range(3):          # 0, 1, 2
    print(i)
 
n = 3
while n > 0:
    n -= 1
 
for i, ch in enumerate("abc"):
    print(i, ch)

Strings

TaskCode
Lengthlen(s)
Upper, lowers.upper(), s.lower(), s.title()
Strip spacess.strip(), s.lstrip(), s.rstrip()
Split, joins.split(","), "-".join(parts)
Replaces.replace("a", "b")
Finds.find("x") (returns -1 if missing), s.index("x")
Tests.startswith("a"), s.endswith("z"), s.isdigit()
Slices[0:3], s[-1], s[::-1]
Counts.count("a")
Python
name = "Ada"
score = 93.456
print(f"{name} scored {score:.1f}")     # Ada scored 93.5
print(f"{score:>10.2f}")                # right aligned
print("a,b,c".split(","))               # ['a', 'b', 'c']
print("-".join(["x", "y"]))             # x-y

Lists

TaskCode
Createnums = [3, 1, 2]
Addnums.append(4), nums.insert(0, 9), nums.extend([5, 6])
Removenums.remove(1), nums.pop(), nums.pop(0), del nums[0]
Sortnums.sort() (in place), sorted(nums) (new list)
Reversenums.reverse(), nums[::-1]
Slicenums[1:3], nums[:2], nums[-2:]
Infolen(nums), min(nums), max(nums), sum(nums)
Searchnums.index(2), nums.count(2), 2 in nums
Copynums.copy() or nums[:]

Tuples

Tuples are immutable lists: point = (3, 4). Unpack them with x, y = point.

Dictionaries

TaskCode
Created = {"a": 1, "b": 2}
Readd["a"], d.get("z", 0)
Setd["c"] = 3
Deletedel d["a"], d.pop("b")
Loopd.keys(), d.values(), d.items()
Merged1 | d2, d.update(other)
Check key"a" in d
Python
prices = {"apple": 3, "pear": 5}
for fruit, price in prices.items():
    print(fruit, price)
 
counts = {}
for ch in "banana":
    counts[ch] = counts.get(ch, 0) + 1
print(counts)       # {'b': 1, 'a': 3, 'n': 2}

Sets

TaskCode
Creates = {1, 2, 3}, set([1, 1, 2]), empty: set()
Add, removes.add(4), s.discard(1)
Uniona | b
Intersectiona & b
Differencea - b
Symmetric differencea ^ b

Sets hold unique values and check membership very quickly. Use them to remove duplicates: list(set(items)).

Comprehensions

Python
squares = [n * n for n in range(5)]                 # [0, 1, 4, 9, 16]
evens = [n for n in range(10) if n % 2 == 0]        # [0, 2, 4, 6, 8]
lengths = {w: len(w) for w in ["hi", "python"]}     # dict comprehension
unique = {c for c in "hello"}                       # set comprehension
total = sum(n for n in range(100))                  # generator expression

Functions

Python
def greet(name, greeting="Hello"):
    """Return a greeting."""
    return f"{greeting}, {name}!"
 
def total(*numbers, **options):
    return sum(numbers)
 
square = lambda x: x * x
 
print(greet("Ada"))
print(greet("Ada", greeting="Hi"))
print(total(1, 2, 3))
print(list(map(square, [1, 2, 3])))
ConceptSyntax
Default argumentdef f(a, b=2)
Variable positionaldef f(*args)
Variable keyworddef f(**kwargs)
Unpack callf(*items), f(**options)
Type hintsdef f(a: int) -> str
Lambdalambda x: x + 1

Never use a mutable default such as def f(items=[]). Use None and create the list inside the function.

Classes

Python
class Dog:
    species = "canine"            # class attribute
 
    def __init__(self, name):
        self.name = name          # instance attribute
 
    def speak(self):
        return f"{self.name} says woof"
 
    def __repr__(self):
        return f"Dog({self.name!r})"
 
class Puppy(Dog):                 # inheritance
    def speak(self):
        return super().speak() + " softly"
 
print(Puppy("Rex").speak())
MethodPurpose
__init__Set up a new object
__str__, __repr__Readable and debug text
__len__Support len(obj)
__eq__Support ==
@staticmethodMethod with no self
@classmethodMethod that receives the class
@propertyMethod used like an attribute

Files

Python
with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("hello\n")
 
with open("notes.txt", encoding="utf-8") as f:
    for line in f:
        print(line.strip())
ModeMeaning
"r"Read (default)
"w"Write, replaces the file
"a"Append
"rb", "wb"Binary read and write

Exceptions

Python
try:
    value = int("abc")
except ValueError as err:
    print("bad number:", err)
except (TypeError, KeyError):
    print("type or key problem")
else:
    print("no error")
finally:
    print("always runs")
 
raise ValueError("something is wrong")
Common exceptionTypical cause
ValueErrorRight type, wrong value, such as int("x")
TypeErrorWrong type, such as 1 + "a"
KeyErrorMissing dict key
IndexErrorList index out of range
FileNotFoundErrorFile does not exist
ZeroDivisionErrorDivision by zero

Common standard library

ModuleHandy forExample
mathMaths functionsmath.sqrt(16)
randomRandom numbersrandom.choice(items)
datetimeDates and timesdatetime.now()
jsonJSON textjson.loads(text), json.dumps(obj)
os, pathlibPaths and foldersPath("a") / "b.txt"
sysInterpreter infosys.argv
reRegular expressionsre.findall(r"\d+", s)
collectionsCounter, defaultdict, dequeCounter("banana")
itertoolsIteration helpersitertools.chain(a, b)
csvCSV filescsv.reader(f)
Python
from collections import Counter
from pathlib import Path
import json
 
print(Counter("banana").most_common(1))     # [('a', 3)]
print(json.dumps({"a": 1}))                 # {"a": 1}
print(Path("data") / "file.txt")

Handy built-ins

len, range, enumerate, zip, sorted, reversed, sum, min, max, any, all, map, filter, abs, round, input, print, open, isinstance.

Python
>>> list(zip([1, 2], ["a", "b"]))
[(1, 'a'), (2, 'b')]
>>> any(n > 2 for n in [1, 2, 3])
True

Check what you learned

quizCheck yourself
  1. What does [n * n for n in range(4)] produce?

    Show answer

    B — [0, 1, 4, 9] — range(4) yields 0, 1, 2, 3 and each one is squared, giving 0, 1, 4, 9.

  2. Which is the safest way to read a dictionary key that might be missing?

    Show answer

    B — d.get(key, default) — d.get returns the default instead of raising KeyError when the key is absent.

  3. Why use a with statement to open a file?

    Show answer

    C — It closes the file automatically, even if an error happens — with is a context manager. It guarantees the file is closed when the block ends, whether it ends normally or with an exception.

Credits

The original printable memento below is by Laurent Pointal.

Python Cheat Sheet 1 Python Cheat Sheet 2

Was this page helpful?

Let us know how we did