This Python cheat sheet covers the basics — variables, data structures, loops, functions and common string methods — for quick reference.
Basics
| Code | What it does |
|---|---|
| x = 5 | Variable |
| print(x) | Output |
| len(s) | Length |
| type(x) | Type of a value |
| range(5) | 0,1,2,3,4 |
| input() | Read a line |
Data structures
| Code | What it does |
|---|---|
| lst = [1, 2, 3] | List |
| d = {"a": 1} | Dictionary |
| t = (1, 2) | Tuple |
| s = {1, 2} | Set |
| lst.append(x) | Add to list |
| d.get("a") | Dict value |
| [x*2 for x in lst] | List comprehension |
Control flow
| Code | What it does |
|---|---|
| if x > 0: | Condition |
| for i in lst: | Loop over items |
| while x < 5: | While loop |
| def f(a, b): | Define a function |
| return x | Return a value |