Back to Cheatsheet Grid
Python 10 Snippets

Python Syntax Cheatsheet

Comprehensive core syntax, data structures, list comprehensions, OOP patterns, and common built-in library functions.

Data Structures & Logic

[x**2 for x in range(10)]

Create a list of squared numbers dynamically.

squares = [x**2 for x in range(10)]
{k: v for k, v in zip(keys, values)}

Zip lists and map them into a new dictionary.

mapping = {k: v for k, v in zip(["a","b"], [1,2])}
list(filter(lambda x: x > 5, arr))

Extract subset from array matching conditional lambda function.

vals = list(filter(lambda x: x > 5, [2, 8, 4, 9]))

File IO & Serialization

with open("file.txt", "r") as f:

Open, parse text files, and close context safely.

with open("app.log", "r") as f: lines = f.readlines()
json.loads(json_str)

Convert raw JSON strings into structured dictionaries.

import json\ndata = json.loads('{"status":"ok"}')
json.dumps(dict_data)

Serialize dictionaries into formatted JSON string objects.

import json\njson_str = json.dumps({"active": True}, indent=4)

Exception Handling

try: ... except Exception as e:

Catch and log execution errors to shield app processes.

try: res = 10 / 0 except ZeroDivisionError as e: print(f"Error: {e}")
isinstance(obj, ClassName)

Verify object types before calling properties.

isinstance(user_dict, dict)
decorators: @classmethod

Annotate methods to interact directly with classes.

@classmethod def parse_db(cls, val): return cls(val)
generators: yield val

Generate sequence generators that preserve memory usage.

def count(n): while n > 0: yield n n -= 1