---
title: "Python Essentials Cheatsheet | FindUtils"
description: "Python syntax, data structures, comprehensions, built-in functions, and common patterns"
url: https://findutils.com/cheatsheets/python-essentials/
---

# Python Essentials Cheatsheet

Python syntax, data structures, comprehensions, built-in functions, and common patterns 59 commands in 8 sections, filed under [Programming](https://findutils.com/cheatsheets/programming/).

## Data Types & Variables

- `x = 10`: Integer
- `x = 3.14`: Float
- `x = "hello"`: String
- `x = True / False`: Boolean
- `x = None`: NoneType (null equivalent)
- `type(x)`: Get type of variable
- `isinstance(x, int)`: Check if instance of type
- `int() float() str() bool()`: Type conversion functions

## Strings

- `f"Hello {name}"`: f-string (formatted string literal)
- `s.upper() / s.lower()`: Convert case
- `s.strip()`: Remove leading/trailing whitespace
- `s.split(",")  / ",".join(lst)`: Split string / join list
- `s.replace("old", "new")`: Replace substring
- `s.startswith() / s.endswith()`: Check prefix/suffix
- `s.find("sub")`: Find substring index (-1 if not found)
- `s[1:5]`: Slice string (index 1 to 4)
- `s[::-1]`: Reverse string

## Lists

- `lst = [1, 2, 3]`: Create list
- `lst.append(4)`: Add element to end
- `lst.insert(0, "first")`: Insert at index
- `lst.pop() / lst.pop(0)`: Remove last / at index
- `lst.remove(val)`: Remove first occurrence of value
- `lst.sort() / sorted(lst)`: Sort in-place / return sorted copy
- `lst.reverse()`: Reverse in-place
- `len(lst)`: Number of elements
- `val in lst`: Check if value exists
- `[x*2 for x in lst]`: List comprehension
- `[x for x in lst if x > 0]`: Filtered list comprehension

## Dictionaries

- `d = {"key": "val"}`: Create dictionary
- `d["key"] / d.get("key", default)`: Access value / with default
- `d.keys() / d.values() / d.items()`: Get keys / values / pairs
- `d.update(other)`: Merge another dict into d
- `d.pop("key")`: Remove and return value
- `"key" in d`: Check if key exists
- `{k: v for k, v in items}`: Dict comprehension
- `d | other`: Merge dicts (Python 3.9+)

## Control Flow

- `if x > 0: ... elif: ... else:`: Conditional
- `for item in iterable:`: For loop
- `for i, val in enumerate(lst):`: Loop with index
- `for k, v in d.items():`: Loop over dict items
- `while condition:`: While loop
- `break / continue / pass`: Loop control
- `x if condition else y`: Ternary expression
- `match value: case pattern:`: Structural pattern matching (3.10+)

## Functions

- `def fn(a, b="default"):`: Function with default parameter
- `def fn(*args, **kwargs):`: Variable arguments
- `lambda x: x * 2`: Anonymous function
- `map(fn, iterable)`: Apply function to each element
- `filter(fn, iterable)`: Filter elements by function
- `@decorator`: Function decorator syntax
- `def fn() -> int:`: Type hint for return value

## File I/O & Error Handling

- `with open("f.txt") as f:`: Open file (auto-close)
- `f.read() / f.readlines()`: Read entire file / as lines
- `f.write("text")`: Write to file
- `try: ... except Exception as e:`: Try/except block
- `try: ... finally:`: Always-run cleanup block
- `raise ValueError("msg")`: Raise an exception

## Sources

- `https://docs.python.org/3/reference/`: Python 3 language reference: syntax and execution rules.
- `https://docs.python.org/3/library/`: Python 3 standard library: built-in types, functions, and file operations.

## Related

- Cheatsheet: [Barcode Formats](https://findutils.com/cheatsheets/barcode-formats/)
- Cheatsheet: [JavaScript ES6+](https://findutils.com/cheatsheets/javascript-es6/)
- Cheatsheet: [Regular Expressions](https://findutils.com/cheatsheets/regex/)
- Tool: [JSON to Python Class](https://findutils.com/developers/json-to-python-class/)
