Real Programs
Python Cheat Sheet
Python on one page: syntax, built-in types and their methods, comprehensions, functions, files, exceptions, classes and the standard-library modules you will reach for most.
Syntax at a glance
Python
x = 10 # variables: no declarations
if x > 5: ... # if / elif / else, indentation blocks
for i in range(n): ... # loop over a range or any iterable
while cond: ... # break, continue, loop-else
def f(a, b=2, *args, **kwargs): # functions with defaults and varargs
return a + b
lambda x: x * 2 # anonymous function
class Dog(Animal): # class with inheritance
def __init__(self, name):
super().__init__(name)
try: ... except ValueError as e: ... else: ... finally: ...
with open("f.txt") as f: ... # auto-closing resourcesBuilt-in types
| Type | Literal | Mutable | Ordered | Notes |
|---|---|---|---|---|
int, float, bool |
3, 3.0, True |
no | — | int has unlimited size |
str |
"hi" |
no | yes | slicing, methods, f-strings |
list |
[1, 2] |
yes | yes | dynamic array |
tuple |
(1, 2) |
no | yes | fixed records, dict keys |
set |
{1, 2} |
yes | no | unique items, O(1) in |
dict |
{"k": 1} |
yes | insertion order | key → value, O(1) lookup |
Most-used methods
| Type | Methods |
|---|---|
str |
split, join, strip, replace, find, count, upper, lower, startswith, isdigit |
list |
append, extend, insert, pop, remove, sort, reverse, index, count, copy |
dict |
get, items, keys, values, pop, setdefault, update |
set |
add, discard, remove, union (|), intersection (&), difference (-) |
Built-in functions
len, range, enumerate, zip, sorted, reversed, sum, min, max, abs, round, map, filter, any, all, isinstance, type, input, print, int, float, str, list, dict, set, tuple, open, ord, chr
Comprehensions
Python
[x * x for x in xs if x > 0] # list
{x % 3 for x in xs} # set
{k: v for k, v in pairs} # dict
sum(x for x in xs) # generator expressionSlicing
| Expression | Meaning |
|---|---|
s[a:b] |
from a up to (not including) b |
s[:n] / s[-n:] |
first n / last n items |
s[::-1] |
reversed copy |
s[::2] |
every second item |
Python vs C quick map
| C | Python |
|---|---|
printf("%d\n", x); |
print(x) |
scanf("%d", &x); |
x = int(input()) |
for (i = 0; i < n; i++) |
for i in range(n): |
a && b, a || b, !a |
a and b, a or b, not a |
x++ |
x += 1 |
NULL |
None |
struct |
class / @dataclass |
malloc / free |
automatic memory management |
Programs to practise
- Number programs: prime, factorial, Fibonacci, palindrome, Armstrong, GCD/LCM.
- String programs: reverse words, palindrome sentence, vowel count, anagram check, character frequency.
- List programs: second largest, remove duplicates keeping order, rotate, merge sorted lists.
- Dictionary programs: word frequency, group by first letter, invert a dict, student grade book.
- Recursion: power, sum of digits, flatten nested lists, permutations.
- Files: count lines/words/characters, CSV average, JSON save/load.
- OOP: BankAccount with validation, Shape hierarchy, Vector with dunder methods.
- Generators: Fibonacci generator, reading a large file lazily.
Final check: mixed revision
4 questions · pick an answer to check it instantly
- 1
What is
[1, 2, 3, 4, 5][-2:]?A negative start counts from the end; the slice runs to the end. - 2
Which is mutable?
Lists, dicts and sets can change in place. - 3
What does
{x: x ** 2 for x in range(3)}produce?A dict comprehension with keys 0, 1, 2 and their squares. - 4
Which statement creates an object of
class Carwith__init__(self, model)?Calling the class runs__init__with the new object asself.