# Python Basics Cheat Sheet This cheat sheet covers fundamental operations for Python Lists, Dictionaries, Tuples, and the functional concepts `map`, `filter`, and `reduce`. --- ## Lists (`list`) * **Description:** Ordered, mutable (changeable) sequence of items. * **Syntax:** `my_list = [item1, item2, ...]` **Common Operations:** * **Creation:** * `empty = []` * `nums = [1, 2, 3]` * **Access (Index):** `my_list[index]` (0-based) * `first = my_list[0]` * `last = my_list[-1]` * **Slicing:** `my_list[start:stop:step]` (stop is exclusive) * `sub = my_list[1:4]` (items at index 1, 2, 3) * `copy = my_list[:]` * `reverse = my_list[::-1]` * **Length:** `len(my_list)` * **Add Items:** * `my_list.append(item)` (adds to end) * `my_list.insert(index, item)` (inserts at index) * `list1 + list2` (concatenates, creates new list) * **Remove Items:** * `my_list.remove(value)` (removes first occurrence of `value`) * `item = my_list.pop(index)` (removes and returns item at `index`, default is last) * `del my_list[index]` (deletes item at `index`) * `del my_list[start:stop]` (deletes slice) * **Modify Item:** `my_list[index] = new_value` * **Membership:** `item in my_list`, `item not in my_list` (returns `True`/`False`) * **Sorting:** * `my_list.sort()` (sorts in-place) * `new_list = sorted(my_list)` (returns new sorted list) * **Reversing:** `my_list.reverse()` (reverses in-place) * **Counting:** `my_list.count(value)` * **Finding Index:** `my_list.index(value)` (returns index of first occurrence) --- ## Dictionaries (`dict`) * **Description:** Unordered (Python < 3.7) or ordered (Python >= 3.7) collection of key-value pairs. Keys must be unique and immutable. Mutable. * **Syntax:** `my_dict = {key1: value1, key2: value2, ...}` **Common Operations:** * **Creation:** * `empty = {}` * `person = {"name": "Alice", "age": 30}` * **Access Value:** * `value = my_dict[key]` (raises `KeyError` if key not found) * `value = my_dict.get(key, default_value)` (returns `default_value` or `None` if key not found) * **Add/Update Item:** * `my_dict[key] = value` * `my_dict.update({key1: val1, key2: val2})` * **Remove Items:** * `value = my_dict.pop(key)` (removes item, returns value, raises `KeyError` if key not found) * `key_value_pair = my_dict.popitem()` (removes and returns last inserted item in Python >= 3.7) * `del my_dict[key]` (deletes item) * `my_dict.clear()` (removes all items) * **Length:** `len(my_dict)` (number of key-value pairs) * **Membership (Keys):** `key in my_dict`, `key not in my_dict` * **Views (Iterators):** * `my_dict.keys()` (view of keys) * `my_dict.values()` (view of values) * `my_dict.items()` (view of key-value tuple pairs) * Use `list()` to convert views to lists: `list(my_dict.keys())` --- ## Tuples (`tuple`) * **Description:** Ordered, **immutable** (unchangeable) sequence of items. * **Syntax:** `my_tuple = (item1, item2, ...)` or `my_tuple = item1, item2, ...` * Single item tuple: `single = (item,)` (note the comma!) **Common Operations:** * **Creation:** * `empty = ()` * `coords = (10, 20)` * `single = (99,)` * **Access (Index):** `my_tuple[index]` * **Slicing:** `my_tuple[start:stop:step]` (creates a *new* tuple) * **Length:** `len(my_tuple)` * **Membership:** `item in my_tuple`, `item not in my_tuple` * **Concatenation:** `tuple1 + tuple2` (creates a *new* tuple) * **Repetition:** `my_tuple * n` (creates a *new* tuple) * **Counting:** `my_tuple.count(value)` * **Finding Index:** `my_tuple.index(value)` * **Unpacking:** `var1, var2 = my_tuple` (assigns items to variables) * **Immutability:** Cannot change, add, or remove items after creation. --- ## Functional Concepts (`map`, `filter`, `reduce`) * Often used with `lambda` functions: `lambda arguments: expression` **`map(function, iterable, ...)`:** * **Purpose:** Applies `function` to every item of `iterable`. * **Returns:** A map object (iterator). Use `list()` to see results. * **Example:** `squares = list(map(lambda x: x * x, [1, 2, 3]))` # `squares` is `[1, 4, 9]` **`filter(function, iterable)`:** * **Purpose:** Filters items from `iterable` where `function` returns `True`. * **Returns:** A filter object (iterator). Use `list()` to see results. * **Example:** `evens = list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4]))` # `evens` is `[2, 4]` **`reduce(function, iterable[, initializer])`:** * **Purpose:** Applies `function` cumulatively to items of `iterable`, reducing it to a single value. `function` must take two arguments. * **Location:** Needs `from functools import reduce` * **Returns:** A single accumulated value. * **Example:** `product = reduce(lambda x, y: x * y, [1, 2, 3, 4])` # `product` is `24` * **Example with Initializer:** `sum_plus_10 = reduce(lambda x, y: x + y, [1, 2, 3], 10)` # `sum_plus_10` is `16`