Python Cheat Sheet
# Numeric: int, float, complex
# Boolean: bool
# Sequence: str, list, tuple
# Set: set, frozenset
# Mapping: dict
# None: NoneType
# Binary: bytes, bytearray, memoryview
# Checking: type()
| Category | Data Type | Example |
|---|---|---|
| Numeric | int | 10 |
float | 3.14 | |
complex | 2+3j | |
| Boolean | bool | True |
| Sequence | str | "Hello" |
list | [1, 2, 3] | |
tuple | (1, 2, 3) | |
| Set | set | {1, 2, 3} |
frozenset | frozenset([1,2,3]) | |
| Mapping | dict | {"a": 1} |
| None | NoneType | None |
| Binary | bytes | b"ABC" |
bytearray | bytearray(5) | |
memoryview | memoryview(b"ABC") | |
| Checking | type() | print(type(10)) β <class 'int'> |
| Category | Type | Example |
|---|---|---|
| Numeric | int, float, complex | 10, 3.14, 2+3j |
| Boolean | bool | True / False |
| Sequence | str, list, tuple | "Hello", [1,2,3], (1,2,3) |
| Set | set, frozenset | {1,2,3}, frozenset([1,2,3]) |
| Mapping | dict | {"a":1} |
| None | NoneType | None |
| Binary | bytes, bytearray, memoryview | b"ABC", bytearray(5), memoryview(b"ABC") |
| Checking | type() | type(10) β <class 'int'> |
Tip: Python is dynamically typed β no need to declare type before assignment. Use type() or isinstance() to check types at runtime.
| Feature | List | Tuple | Set | Dictionary |
|---|---|---|---|---|
| Symbol | [] | () | {} | {key:value} |
| Mutable | Yes | No | Yes | Yes |
| Insertion order | Preserved | Preserved | Not preserved | Preserved |
| Duplicates | Allowed | Allowed | Not allowed | Keys β / Values β |
| Heterogeneous | Allowed | Allowed | Allowed | Allowed |
| Indexing | Yes | Yes | No | By keys |
| Empty creation | [] | () | set() | {} |
# Examples
my_list = [1, 2, "hello", 3.14]
my_list.append(5) # modify
my_tuple = (1, 2, "hello", 3.14)
# my_tuple[0] = 5 # ERROR! immutable
my_set = {1, 2, 3, 3} # {1, 2, 3}
my_set.add(4)
my_dict = {"name": "Alice", "age": 25}
my_dict["city"] = "NYC"
| Need | Use | Why |
|---|---|---|
| Ordered + mutable | list | Can add/remove/change items |
| Ordered + immutable | tuple | Safe from changes, faster |
| Unique items only | set | Auto-removes duplicates |
| Key-value pairs | dict | Fast lookups by key |
Note: Tuples can be used as dictionary keys (if they contain only immutable items), but lists cannot.
| Function | Description | Example | Output |
|---|---|---|---|
type() | Returns data type | type(10) | <class 'int'> |
len() | Returns length | len("hello") | 5 |
id() | Memory address | id("test") | unique ID |
str() | Convert to string | str(123) | '123' |
int() | Convert to integer | int("45") | 45 |
float() | Convert to float | float("3.14") | 3.14 |
bool() | Convert to boolean | bool(0) | False |
list() | Convert to list | list((1,2,3)) | [1, 2, 3] |
tuple() | Convert to tuple | tuple([1,2,3]) | (1, 2, 3) |
set() | Convert to set | set([1,1,2]) | {1, 2} |
dict() | Create dictionary | dict([("a",1),("b",2)]) | {'a':1,'b':2} |
sorted() | Returns sorted list | sorted([3,1,2]) | [1, 2, 3] |
min() | Minimum | min([5,2,8]) | 2 |
max() | Maximum | max([5,2,8]) | 8 |
sum() | Sum | sum([1,2,3]) | 6 |
abs() | Absolute value | abs(-10) | 10 |
round() | Rounds number | round(3.14159, 2) | 3.14 |
isinstance() | Checks type | isinstance(10, int) | True |
hash() | Returns hash value | hash("hello") | integer |
len(), type(), id(), str(), int(), float(), bool(), list(), tuple(), set(), dict(), sorted(), min(), max(), sum(), abs(), round(), isinstance(), hash(), callable(), chr(), ord(), bin(), oct(), hex(), dir(), help(), eval(), exec(), input(), print(), open(), range(), enumerate(), zip(), filter(), map(), reversed(), slice(), iter(), next(), any(), all(), delattr(), getattr(), setattr(), hasattr(), globals(), locals(), vars(), __import__(), compile(), memoryview(), property(), staticmethod(), classmethod(), super(), repr(), ascii(), format(), frozenset(), bytearray(), bytes()
Most used: len(), type(), range(), print(), input(), enumerate(), zip(), sorted(), map(), filter()
| Method | Description | Example | Output |
|---|---|---|---|
.upper() | Uppercase | "hello".upper() | 'HELLO' |
.lower() | Lowercase | "HELLO".lower() | 'hello' |
.capitalize() | First char uppercase | "hello".capitalize() | 'Hello' |
.title() | Each word capitalized | "hello world".title() | 'Hello World' |
.strip() | Removes whitespace | " hi ".strip() | 'hi' |
.replace() | Replaces substring | "hello".replace("l","x") | 'hexxo' |
.split() | Splits into list | "a,b,c".split(",") | ['a','b','c'] |
.join() | Joins iterable | ",".join(['a','b','c']) | 'a,b,c' |
.find() | Finds substring index | "hello".find("e") | 1 |
.count() | Counts occurrences | "hello".count("l") | 2 |
.startswith() | Checks start | "hello".startswith("he") | True |
.endswith() | Checks end | "hello".endswith("lo") | True |
.isdigit() | All digits? | "123".isdigit() | True |
.isalpha() | All alphabets? | "abc".isalpha() | True |
.zfill() | Pads with zeros | "42".zfill(5) | '00042' |
.format() | Formats string | "{} world".format("Hello") | 'Hello world' |
.center() | Centers string | "hi".center(10,"*") | '****hi****' |
.ljust() | Left justifies | "hi".ljust(10,"-") | 'hi--------' |
.rjust() | Right justifies | "hi".rjust(10,"-") | '--------hi' |
.upper(), .lower(), .strip(), .split(), .join(), .rstrip(), .lstrip(), .capitalize(), .title(), .replace(), .find(), .index(), .count(), .startswith(), .endswith(), .isdigit(), .isalpha(), .isalnum(), .islower(), .isupper(), .zfill(), .format(), .center(), .ljust(), .rjust(), .partition(), .rpartition(), .splitlines(), .swapcase(), .casefold(), .encode(), .expandtabs(), .isdecimal(), .isidentifier(), .isnumeric(), .isprintable(), .isspace(), .maketrans(), .translate(), .rsplit(), .rfind(), .rindex(), .format_map()
Most used: .upper(), .lower(), .strip(), .split(), .join(), .replace()
| Method | Description | Example | Output |
|---|---|---|---|
.append() | Adds element to end | lst=[1,2]; lst.append(3) | [1,2,3] |
.extend() | Adds multiple | lst=[1,2]; lst.extend([3,4]) | [1,2,3,4] |
.insert() | Inserts at index | lst=[1,3]; lst.insert(1,2) | [1,2,3] |
.remove() | Removes first occurrence | lst=[1,2,3,2]; lst.remove(2) | [1,3,2] |
.pop() | Removes & returns | lst=[1,2,3]; lst.pop(1) | 2 (β [1,3]) |
.clear() | Removes all | lst=[1,2,3]; lst.clear() | [] |
.index() | Index of element | [1,2,3,2].index(2) | 1 |
.count() | Counts occurrences | [1,2,2,3].count(2) | 2 |
.sort() | Sorts in place | lst=[3,1,2]; lst.sort() | [1,2,3] |
.reverse() | Reverses in place | lst=[1,2,3]; lst.reverse() | [3,2,1] |
.copy() | Shallow copy | lst=[1,2]; lst2=lst.copy() | [1,2] |
# List comprehension (fast, Pythonic) squares = [x*x for x in range(5)] # [0,1,4,9,16] evens = [x for x in range(10) if x%2==0] # Sort with custom key words = ["banana", "apple", "cherry"] words.sort(key=len) # Reverse sort nums = [3, 1, 4, 1, 5] nums.sort(reverse=True) # [5, 4, 3, 1, 1]
Most used: .append(), .extend(), .pop(), .sort(), .reverse(), .remove()
Tuple (immutable β only 2 methods)
| Method | Description | Example | Output |
|---|---|---|---|
.index() | Index of element | (1,2,3,2).index(2) | 1 |
.count() | Counts occurrences | (1,2,2,3).count(2) | 2 |
Set Methods
| Method | Description | Example | Output |
|---|---|---|---|
.add() | Adds single element | s={1,2}; s.add(3) | {1,2,3} |
.update() | Adds multiple | s={1,2}; s.update([3,4]) | {1,2,3,4} |
.remove() | Removes (error if missing) | s={1,2,3}; s.remove(2) | {1,3} |
.discard() | Removes (no error) | s={1,2,3}; s.discard(4) | {1,2,3} |
.pop() | Removes random element | s={1,2,3}; s.pop() | random |
.clear() | Removes all | s.clear() | set() |
.union() / | | Union | {1,2}.union({2,3}) | {1,2,3} |
.intersection() / & | Intersection | {1,2}.intersection({2,3}) | {2} |
.difference() / - | Difference | {1,2}.difference({2,3}) | {1} |
.symmetric_difference() / ^ | Symmetric diff | {1,2}.symmetric_difference({2,3}) | {1,3} |
.issubset() | Subset check | {1}.issubset({1,2}) | True |
.issuperset() | Superset check | {1,2}.issuperset({1}) | True |
.isdisjoint() | No common elements | {1}.isdisjoint({2}) | True |
Dictionary Methods
| Method | Description | Example | Output |
|---|---|---|---|
.keys() | All keys | {"a":1,"b":2}.keys() | dict_keys(['a','b']) |
.values() | All values | {"a":1,"b":2}.values() | dict_values([1,2]) |
.items() | Key-value pairs | {"a":1,"b":2}.items() | dict_items([('a',1),('b',2)]) |
.get() | Value with default | {"a":1}.get("b",0) | 0 |
.setdefault() | Set default if missing | d={}; d.setdefault("a",1) | 1 |
.update() | Update with another | d={"a":1}; d.update({"b":2}) | {'a':1,'b':2} |
.pop() | Remove key & return value | d={"a":1,"b":2}; d.pop("a") | 1 |
.popitem() | Remove last item | d={"a":1,"b":2}; d.popitem() | ('b',2) |
.clear() | Remove all | d.clear() | {} |
.copy() | Shallow copy | d={"a":1}; d2=d.copy() | {'a':1} |
.fromkeys() | Create from keys | dict.fromkeys(['a','b'],0) | {'a':0,'b':0} |
# Set operators a | b # union a & b # intersection a - b # difference a ^ b # symmetric difference # Set comparisons s1.issubset(s2) # s1 β s2 s1.issuperset(s2) # s1 β s2 s1.isdisjoint(s2) # no common elements # Dict comprehension squares = {x: x*x for x in range(5)} # Merge dicts (Python 3.9+) merged = d1 | d2
| Method / Operation | Description | Example | Output |
|---|---|---|---|
.bit_length() | Bits to represent int | (10).bit_length() | 4 |
.to_bytes() | Convert to bytes | (1024).to_bytes(2,"big") | b'\x04\x00' |
.from_bytes() | Int from bytes | int.from_bytes(b'\x04\x00',"big") | 1024 |
.as_integer_ratio() | Ratio as tuple | (3.5).as_integer_ratio() | (7,2) |
.is_integer() | Float is integer? | (5.0).is_integer() | True |
.hex() | Hexadecimal string | (255).hex() | '0xff' |
.real | Real part | (2+3j).real | 2.0 |
.imag | Imaginary part | (2+3j).imag | 3.0 |
.conjugate() | Complex conjugate | (2+3j).conjugate() | (2-3j) |
Boolean: and, or, not, ==, !=, is, is not | |||
# Integer & Float attributes (10).numerator # 10 (10).denominator # 1 # Short-circuit behavior x = 0 or "default" # "default" y = 5 and 10 # 10
Conditional & Loops
if x > 5: print("Big")
if age >= 18: print("Adult") else: print("Minor")
if marks>=90: grade="A" elif marks>=75: grade="B" else: grade="C"
# ternary: "Pass" if score>=40 else "Fail"
while i <= 3: print(i); i += 1
for fruit in ["apple","banana"]: print(fruit)
for i in range(1,4): print(i)
for k,v in d.items(): print(k,v)
# break, continue, pass, loop else
# match-case (Python 3.10+)
match x:
case 1: print("One")
case 2: print("Two")
case _: print("Other")
Slicing
| Slice | Syntax | Example | Output |
|---|---|---|---|
| Basic | [start:stop] | "Python"[1:4] | "yth" |
| Start only | [start:] | "Python"[2:] | "thon" |
| Stop only | [:stop] | "Python"[:3] | "Pyt" |
| Full copy | [:] | "Python"[:] | "Python" |
| With step | [::step] | "Python"[::2] | "Pto" |
| Reverse | [::-1] | "Python"[::-1] | "nohtyP" |
| Negative | [-3:] | "Python"[-3:] | "hon" |
Operators
| Category | Operators |
|---|---|
| Arithmetic | + - * / // % ** |
| Bitwise | & | ^ ~ << >> |
| Comparison | == != < > <= >= |
| Logical | and or not |
| Assignment | = += -= *= /= //= %= **= |
| Membership | in, not in |
| Identity | is, is not |
| Range Format | Example | Sequence |
|---|---|---|
| range(stop) | range(5) | 0,1,2,3,4 |
| range(start, stop) | range(2,6) | 2,3,4,5 |
| range(start, stop, step) | range(1,10,2) | 1,3,5,7,9 |
| range(start, stop, -step) | range(5,0,-1) | 5,4,3,2,1 |
# Special patterns
for i, val in enumerate(["a","b"]): print(i, val)
for n, a in zip(names, ages): print(n, a)
for i in reversed([1,2,3]): print(i)
for i in sorted([3,1,2]): print(i)
Precedence: ** β ~+- β */%// β +- β <<>> β & β ^ β | β comparisons β ==!= β assignments β is/is not β in/not in β not β and β or
def greet(name="World"): return f"Hello {name}"
def add(a, b): return a + b
def sum_all(*args): return sum(args)
def print_info(**kwargs): ...
square = lambda x: x * x
# decorators, generators, closures
def decorator(func):
def wrapper(): print("Before"); func(); print("After")
return wrapper
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
Key: *args, **kwargs, global, nonlocal, lambda, yield, @decorator, type hints.
| Type | Example |
|---|---|
| Lambda | square = lambda x: x*x |
| Filter | list(filter(lambda x: x%2==0, nums)) |
| Map | list(map(lambda x: x**2, [1,2,3])) |
| Recursive | def factorial(n): return 1 if n<=1 else n*factorial(n-1) |
| Closure | def multiplier(n): return lambda x: x*n |
| Decorator w/ args | @repeat(3) β runs function 3 times |
# Special parameters def func(a, b, /): ... # positional only def func(*, a, b): ... # keyword only def func(a, /, b, *, c): ... # combined # Function attributes hello.__name__ # 'hello' hello.__doc__ # docstring add.__annotations__ # {'a': int, 'b': int, 'return': int}
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
except (ValueError, TypeError) as e:
print(f"Error: {e}")
else:
print("Success")
finally:
print("Cleanup")
raise ValueError("Invalid")
class MyError(Exception): pass
assert radius > 0, "Radius must be positive"
Built-in exceptions: ZeroDivisionError, ValueError, TypeError, IndexError, KeyError, FileNotFoundError, etc.
| Type | Example |
|---|---|
| Basic | try: ... except: ... |
| Specific | except ValueError as e: |
| Multiple | except (TypeError, ValueError): |
| Full block | try/except/else/finally |
| Raise | raise ValueError("msg") |
| Re-raise | except: raise |
| Custom | class MyError(Exception): pass |
| Chaining | raise ValueError(...) from e |
| Suppress | with suppress(FileNotFoundError): |
| Assert | assert x > 0, "must be positive" |
Hierarchy: BaseException β Exception β ArithmeticError, LookupError, etc.
class Person:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hi {self.name}"
class Animal:
def speak(self): pass
class Dog(Animal):
def speak(self): return "Woof"
@property
def radius(self): return self.__radius
Pillars: Encapsulation, Inheritance, Polymorphism, Abstraction. __str__, __repr__, @classmethod, @staticmethod, super().
| Pillar | Description |
|---|---|
| Encapsulation | Bundle data + methods; private via __attr |
| Inheritance | class Child(Parent) β reuse code |
| Polymorphism | Same method, different behavior |
| Abstraction | Hide complexity via ABC / interfaces |
# Inheritance types class A: pass class B(A): pass # Single class C(A): pass class D(B, C): pass # Multiple class E(D): pass # Multilevel # Hierarchical: multiple children from one parent # Hybrid: combination of above # Special methods __init__, __str__, __repr__, __len__, __getitem__, __call__, __eq__, __slots__ # Class & static methods @classmethod def create(cls): return cls() @staticmethod def add(a, b): return a + b # Property decorator @property def radius(self): return self.__radius @radius.setter def radius(self, value): self.__radius = value
Polymorphism types: Compile-time (overloading), Runtime (overriding), Duck typing, Operator overloading.
with open("data.txt", "r") as f:
content = f.read()
with open("out.txt", "w") as f:
f.write("Hello")
import json, csv, pickle, os
async def main(): await asyncio.sleep(1)
threading.Thread(target=func).start()
Modes: r, w, a, r+, w+, a+, rb, wb. Context managers, JSON, CSV, pickle, threading, async.
| Mode | Description | Pointer |
|---|---|---|
| r | Read only | Start |
| w | Write (overwrite) | Start |
| a | Append | End |
| r+ | Read & write | Start |
| w+ | Write & read | Start |
| a+ | Append & read | End |
| rb / wb | Binary read / write | β |
# Reading methods f.read(), f.read(n), f.readline(), f.readlines() for line in f: # memory efficient # File methods f.seek(pos), f.tell(), f.close(), f.flush() # OS operations os.path.exists(), os.remove(), os.rename() os.listdir(), os.mkdir(), os.getcwd() # CSV / JSON / Pickle csv.reader(f), csv.writer(f) json.load(f), json.dump(data, f) pickle.dump(data, f), pickle.load(f)
Advanced: iterators, generators, threading, multiprocessing, async/await, memory management, metaclasses, descriptors, context managers, decorators.
| Type | Example |
|---|---|
| Basic | x = 10 |
| Multiple | a, b = 5, 10 |
| Chain | x = y = z = 0 |
| Swap | a, b = b, a |
| Valid names | my_var, _private, var2, MAX_SIZE |
| Invalid names | 2var, my-var, class |
| Scope | local, global, enclosing, built-in |
| Modifiers | global, nonlocal |
| Unpacking | a, b, c = [1, 2, 3] |
| Extended unpacking | first, *rest = [1,2,3,4] |
| Constants | PI = 3.14, MAX_USERS = 100 |
| Special | __name__, __file__, __doc__ |
| Walrus | if (n := len(data)) > 10: |
| Type Hints | age: int = 25 |
| Delete | del x |
# Type checking
type(10) # <class 'int'>
isinstance(10, int) # True
# Memory & identity
x = 10
id(x) # memory address
a = [1,2]; b = [1,2]
a == b # True (value)
a is b # False (identity)
# Special assignments
x = 10 if flag else 0 # ternary
with open("file.txt") as f: data = f.read()
# Swap without temp a, b = b, a # Multiple return x, y = get_coords() # Default dict value value = dict.get(key, default) # Safe key check if 'key' in dict: ... # Short-circuit default name = user_input or "Guest"
Common errors: NameError (undefined), UnboundLocalError, AttributeError, TypeError.
Naming: snake_case (vars), UPPER_CASE (constants), CamelCase (classes), _private, __dunder__.