Python Cheat Sheet
Python syntax reference with data structures, list comprehensions, f-strings, file I/O, and common patterns. Copy-ready examples.
Variables
| Syntax | Description | Example |
|---|---|---|
| Variable assignment (no keyword needed) | name = 'Alice' | |
| Get the type of a variable | type(42) → <class 'int'> | |
| Type casting functions | int('42') → 42 | |
| Check if x is instance of type | isinstance(42, int) → True | |
| Python's null value | x = None | |
| Boolean values (capitalized) | is_valid = True | |
| F-string (formatted string literal) | f'{name} is {age} years old' |
Strings
| Syntax | Description | Example |
|---|---|---|
| Length of string | len('hello') → 5 | |
| Change case | 'hello'.upper() → 'HELLO' | |
| Remove whitespace from both ends | ' hi '.strip() → 'hi' | |
| Split string into list | 'a,b,c'.split(',') → ['a','b','c'] | |
| Join list into string | ', '.join(['a','b']) → 'a, b' | |
| Replace occurrences | 'hello'.replace('l','r') → 'herro' | |
| Check string start/end | 'hello'.startswith('he') → True | |
| Find index of substring (-1 if not found) | 'hello'.find('ll') → 2 | |
| String slicing | 'hello'[1:4] → 'ell' | |
| String formatting | '{} is {}'.format('Pi', 3.14) | |
| Check if substring exists | 'ell' in 'hello' → True | |
| Count occurrences of substring | 'hello'.count('l') → 2 | |
| Title case / capitalize first | 'hello world'.title() → 'Hello World' | |
| Check if digits/letters only | '123'.isdigit() → True |
Lists
| Syntax | Description | Example |
|---|---|---|
| Create a list | fruits = ['apple', 'banana'] | |
| Add item to end | lst.append(4) | |
| Insert at index | lst.insert(0, 'first') | |
| Remove and return item at index | lst.pop() or lst.pop(0) | |
| Remove first occurrence of value | lst.remove('apple') | |
| Sort list in place | [3,1,2].sort() → [1,2,3] | |
| Return new sorted list | sorted([3,1,2]) → [1,2,3] | |
| Reverse list in place | [1,2,3].reverse() → [3,2,1] | |
| List slicing | [1,2,3,4][1:3] → [2,3] | |
| List comprehension | [x**2 for x in range(5)] → [0,1,4,9,16] | |
| Filtered list comprehension | [x for x in range(10) if x%2==0] | |
| Number of items in list | len([1,2,3]) → 3 | |
| Check membership | 2 in [1,2,3] → True | |
| Loop with index and value | for i, val in enumerate(lst): | |
| Pair elements from two lists | list(zip([1,2], ['a','b'])) → [(1,'a'),(2,'b')] |
Dicts
| Syntax | Description | Example |
|---|---|---|
| Create a dictionary | user = {'name': 'Alice', 'age': 30} | |
| Access value by key | d.get('name', 'Unknown') | |
| Set or update a key | d['email'] = 'a@b.com' | |
| Get keys or values | list(d.keys()) | |
| Get key-value pairs | for k, v in d.items(): | |
| Remove and return value | d.pop('age') | |
| Check if key exists | 'name' in user → True | |
| Merge another dict into d | d.update({'age': 31}) | |
| Dict comprehension | {x: x**2 for x in range(5)} |
Control Flow
| Syntax | Description | Example |
|---|---|---|
| Conditional branching | if x > 0: ... elif x == 0: ... else: ... | |
| For loop | for i in range(10): print(i) | |
| While loop | while count < 10: count += 1 | |
| Generate sequence of numbers | range(0, 10, 2) → 0,2,4,6,8 | |
| Exit loop / skip iteration | if x == 5: break | |
| Do nothing (placeholder) | def todo(): pass | |
| Ternary/conditional expression | 'even' if n%2==0 else 'odd' | |
| Exception handling | try: ... except ValueError: ... | |
| Raise an exception | raise ValueError('Invalid input') | |
| Structural pattern matching (3.10+) | match status: case 200: ... |
Functions
| Syntax | Description | Example |
|---|---|---|
| Define a function | def greet(name): return f'Hi {name}' | |
| Default parameter value | def add(a, b=0): return a+b | |
| Variable positional args | def sum(*nums): return sum(nums) | |
| Variable keyword args | def info(**kw): print(kw) | |
| Anonymous function | sorted(lst, key=lambda x: x['name']) | |
| Return from function | return x * 2 | |
| Function decorator | @staticmethod | |
| Apply function to each item | list(map(str, [1,2,3])) → ['1','2','3'] | |
| Filter items by function | list(filter(lambda x: x>0, [-1,0,1])) → [1] |
File I/O
| Syntax | Description | Example |
|---|---|---|
| Open a file | f = open('data.txt', 'r') | |
| Context manager (auto-close) | with open('data.txt') as f: data = f.read() | |
| Read file content | content = f.read() | |
| Write to file | f.write('Hello\
') |
Built-ins
| Syntax | Description | Example |
|---|---|---|
| Print to console | print('Hello', end='') | |
| Read user input | name = input('Name: ') | |
| Absolute value | abs(-42) → 42 | |
| Round to n decimals | round(3.14159, 2) → 3.14 | |
| Minimum / maximum value | max(1, 5, 3) → 5 | |
| Sum all values | sum([1,2,3]) → 6 | |
| Check if any/all are True | any([False, True]) → True | |
| Show documentation | help(str.split) | |
| List attributes and methods | dir(list) |
Frequently asked questions
What's the difference between a list and a tuple?
Lists are mutable (can be changed after creation) and use square brackets [1,2,3]. Tuples are immutable (cannot be changed) and use parentheses (1,2,3). Tuples are faster, can be used as dict keys, and signal that data shouldn't change.
When should I use a dictionary vs a list?
Use a list when you have an ordered collection of items accessed by index. Use a dictionary when you need to look up values by a key (name, ID, etc.). Dictionaries have O(1) lookup time vs O(n) for lists.
What does 'if __name__ == "__main__":' do?
It checks if the file is being run directly (not imported). Code under this block only executes when you run the file as a script, not when it's imported as a module. It's Python's equivalent of a main() function.
What's the difference between 'is' and '=='?
'==' checks if values are equal (value comparison). 'is' checks if two variables point to the exact same object in memory (identity comparison). Use 'is' only for None checks: 'if x is None'. Use '==' for everything else.
How do virtual environments work?
Virtual environments (venv) create isolated Python installations for each project. Use 'python -m venv .venv' to create one, then activate it. Each venv has its own pip and packages, preventing version conflicts between projects.
What are *args and **kwargs?
*args collects extra positional arguments as a tuple: def fn(*args). **kwargs collects extra keyword arguments as a dict: def fn(**kwargs). Together they let a function accept any combination of arguments. Useful for decorators and wrapper functions.
Go from reference to real skills
Cheat sheets are great for quick lookups. Our in-depth courses take you from the fundamentals to professional-level mastery.
Browse all courses