Python Cheat Sheets Quick Reference
Python Cheat Sheets Quick Reference
1. Core Syntax & Basic Types
Variables & Type Assignment
main.pyRunnable## Dynamically-typed assignments integer_val = 42 float_val = 3.14159 string_val = "Technical Reference" boolean_val = True null_val = None ## Multiple assignments x, y, z = 1, 2, 3 x = y = z = 0 # Reassign all variables to a single reference
Basic Type Casts & Conversions
main.pyRunnableint_cast = int("100") # Returns 100 float_cast = float("3.14") # Returns 3.14 str_cast = str(1024) # Returns "1024" bool_cast_empty = bool([]) # Returns False (empty containers are falsy) bool_cast_filled = bool([0]) # Returns True (non-empty containers are truthy)
2. Collections & Data Structures
Lists (Mutable Sequences)
- Time Complexities: Access , Append , Insert , Delete , Search .
main.pyRunnableitems = [1, 2, 3] items.append(4) # Append to end: [1, 2, 3, 4] items.insert(0, 99) # Insert at index 0: [99, 1, 2, 3, 4] items.remove(2) # Remove first occurrence of value 2 popped_val = items.pop() # Pop from end, returns popped value items.sort() # Sort in-place cloned_list = items[:] # Shallow copy slice syntax
Dictionaries (Hash Maps)
- Time Complexities: Get/Set average, Delete average.
main.pyRunnablelookup = {"SKU-1": 10.50, "SKU-2": 24.99} lookup["SKU-3"] = 5.00 # Insert key-value pair val = lookup.get("SKU-9", 0.0) # Safe access with default fallback del lookup["SKU-1"] # Delete key ## Dictionary iterations for key in lookup: pass # Iterate keys for key, value in lookup.items(): pass # Iterate key-value pairs
Sets (Unique Unordered Collections)
- Time Complexities: Add/Remove/Membership average.
main.pyRunnableunique_skus = {"SKU-1", "SKU-2"} unique_skus.add("SKU-3") unique_skus.remove("SKU-1") ## Set operations set_a = {1, 2, 3} set_b = {3, 4, 5} union_set = set_a | set_b # {1, 2, 3, 4, 5} intersect_set = set_a & set_b # {3} difference_set = set_a - set_b # {1, 2}
Tuples (Immutable Sequences)
- Time Complexities: Access .
main.pyRunnablerecord = ("CPU-9", 150.00, 10) sku, cost, quantity = record # Unpacking syntax single_element_tuple = (42,) # Requires trailing comma
3. Control Structures & Comprehensions
Conditional Branches
main.pyRunnableif score >= 90: grade = "A" elif score >= 80: grade = "B" else: grade = "C" ## Ternary assignment result = "Pass" if score >= 60 else "Fail"
Iteration Loops
main.pyRunnable## For loop with range bounds for i in range(0, 10, 2): # start, stop, step (0, 2, 4, 6, 8) pass ## Iterating index and value concurrently for idx, item in enumerate(["A", "B", "C"]): pass ## Iterating multiple sequences simultaneously for name, price in zip(["Screen", "Lens"], [150.0, 50.0]): pass ## While loop with conditional escape count = 0 while count < 5: if count == 3: break count += 1 else: # Executes only if loop completes without hitting a 'break' pass
Comprehensions & Generators
main.pyRunnable## List comprehension squared_evens = [x**2 for x in range(10) if x % 2 == 0] ## Dict comprehension sku_lookup = {f"SKU-{x}": x * 10 for x in range(3)} ## Set comprehension unique_lengths = {len(w) for w in ["apple", "grape", "orange"]} ## Generator expression (memory optimized) lazy_squares = (x**2 for x in range(1000000))
4. Functions & Lambda Operations
Function Parameters & Scopes
main.pyRunnabledef process_data(required_arg, default_arg="standard", *args, **kwargs): """ *args: captures additional positional arguments as a tuple. **kwargs: captures additional keyword arguments as a dictionary. """ return required_arg, default_arg, args, kwargs ## Global vs. Local scopes value = 100 def modify_scope(): global value value = 200 # Modifies global variable
Lambda Functions
main.pyRunnable## Inline anonymous functions add_numbers = lambda a, b: a + b result = add_numbers(10, 5) # 15 ## Sorting collections using lambda key functions items = [("Part-A", 15.0), ("Part-B", 5.0)] items.sort(key=lambda x: x[1]) # Sorts ascending by price
5. String Manipulation
Formatting & Slicing
main.pyRunnable## F-string interpolation sku = "MCU-101" price = 5.75 formatted = f"Item: {sku:<10} | Price: ${price:.2f}" ## String Slicing [start:stop:step] text = "PythonFoundations" substring = text[0:6] # "Python" reversed_text = text[::-1] # "snoitadnuoFnohtyP" last_two = text[-2:] # "ns"
Core String Methods
main.pyRunnableraw = " isolated, data, block " clean = raw.strip() # Remove leading/trailing spaces tokens = clean.split(", ") # ["isolated", "data", "block"] rebuilt = " - ".join(tokens) # "isolated - data - block" replaced = clean.replace("data", "x") # "isolated, x, block" has_suffix = clean.endswith("block") # True is_digit_string = "12345".isdigit() # True
6. File I/O & Exception Operations
Path Manipulation (pathlib)
main.pyRunnablefrom pathlib import Path ## Path resolutions directory_path = Path("public/courses") file_path = directory_path / "metadata.json" # Overloaded division operator if file_path.is_file(): print(f"File exists. Size: {file_path.stat().st_size} bytes.")
Stream Operations & Context Managers
main.pyRunnable## Writing to a text file with open("output.txt", "w", encoding="utf-8") as stream: stream.write("First line of record.\n") stream.write("Second line of record.\n") ## Reading from a text file with open("output.txt", "r", encoding="utf-8") as stream: file_contents = stream.read() # Loads entire file ## Streaming line-by-line (memory safe) with open("output.txt", "r", encoding="utf-8") as stream: for line in stream: process_line = line.strip()
Exception Safety Blocks (EAFP)
main.pyRunnabletry: with open("vault.json", "r") as stream: data = stream.read() except FileNotFoundError as error: print(f"Error: File missing. Details: {error}") except OSError as error: print(f"System I/O Failure: {error}") finally: print("Completed execution transaction.")
7. Pure Python Standard Libraries Reference
JSON Serialization (json)
main.pyRunnableimport json ## Encoding dictionary to string payload = {"sku": "MCU-1", "cost": 1.50} json_string = json.dumps(payload, indent=4) ## Decoding string to dictionary decoded_dict = json.loads(json_string) ## Reading/Writing JSON file streams with open("database.json", "w") as f: json.dump(payload, f, indent=4) with open("database.json", "r") as f: data = json.load(f)
Logging Framework (logging)
main.pyRunnableimport logging ## Setup basic configuration logger logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s" ) logging.debug("Diagnostic telemetry - excluded unless log level is DEBUG.") logging.info("Informational event record.") logging.warning("Non-fatal anomalies detected.") logging.error("Fatal transaction failures.")
Copy Operations (copy)
main.pyRunnableimport copy original_nested = [[1, 2], [3, 4]] shallow_clone = copy.copy(original_nested) # Sub-lists references are shared deep_clone = copy.deepcopy(original_nested) # Copies both container and sub-elements
8. Common Patterns & Idioms
EAFP vs. LBYL
- EAFP: Easier to Ask for Forgiveness than Permission. Python's standard programming paradigm.
main.pyRunnable## Recommended (EAFP) try: val = dict_data["key"] except KeyError: val = "default" ## Avoid (LBYL - Look Before You Leap) if "key" in dict_data: val = dict_data["key"] else: val = "default"
Properties Decorators (Getter/Setter)
main.pyRunnableclass TemperatureSensor: def __init__(self, celsius: float): self._celsius = celsius @property def celsius(self) -> float: return self._celsius @celsius.setter def celsius(self, value: float): if value < -273.15: raise ValueError("Temperature below absolute zero is physically impossible.") self._celsius = value
9. Error Resolution Guide
| Exception Name | Common Root Causes | Example Resolution Actions |
|---|---|---|
SyntaxError | Invalid syntax structure (missing colons, unclosed brackets). | Check line formatting details and bracket nesting. |
IndentationError | Inconsistent indentation sizes or mixed tabs and spaces. | Standardize all code layers to 4 spaces indent patterns. |
NameError | Accessing an undefined identifier or variable. | Check identifier spelling and local scope bounds. |
TypeError | Invoking operations on incompatible data types (e.g. int + str). | Apply explicit type casts (e.g. str() or int()). |
ValueError | Parameter holds correct type but invalid values (e.g. int("abc")). | Wrap input processing inside robust validation loops. |
IndexError | Attempting to access an index beyond sequence boundaries. | Verify sequence size utilizing len() beforehand. |
KeyError | Accessing a non-existent dictionary key. | Use dict.get(key, default) for safe lookup operations. |
FileNotFoundError | Attempting to open a missing file path. | Validate path structures using path.is_file() or path checks. |
Reference Readiness Check
Finished this lesson?
Mark it complete to advance your curriculum progress.
23 / 23