PYTHON QUICK REFERENCE
Core Syntax, Data Structures, and Idioms
1. Variables & Basic Types
x = 5 # int y = 3.14 # float name = "Ada" #
str is_ready = True # bool nothing = None # NoneType
2. Core Data Structures
Lists (ordered, mutable)
nums = [1, 2, 3] [Link](4) nums[0] # 1 nums[-1] # 4 nums[1:3]
# [2, 3]
Dictionaries (key-value)
person = {"name": "Ada", "age": 30} person["age"] # 30
[Link]("city", "?") # "?" if missing for k, v in [Link]():
print(k, v)
Tuples & Sets
point = (3, 4) # immutable unique = {1, 2, 2, 3} # {1, 2, 3}
3. Control Flow
if x > 0: print("positive") elif x == 0: print("zero") else:
print("negative") for i in range(5): print(i) while x > 0: x -= 1
4. Functions
def greet(name, greeting="Hello"): return f"{greeting}, {name}!"
greet("Ada") # "Hello, Ada!" greet("Ada", "Hi") # "Hi,
Ada!"
Functions are first-class objects — they can be assigned to variables, passed as arguments, and returned from
other functions.
5. List Comprehensions
squares = [n**2 for n in range(10)] evens = [n for n in range(20) if n % 2 == 0]
pairs = {n: n**2 for n in range(5)} # dict comprehension
Comprehensions are generally faster and more idiomatic than manual for-loops with .append() for simple
transformations.
6. Classes & Objects
class Animal: def __init__(self, name, sound): [Link] = name
[Link] = sound def speak(self): return f"{[Link]} says
{[Link]}" dog = Animal("Rex", "Woof") print([Link]())
7. Error Handling
try: result = 10 / 0 except ZeroDivisionError as e: print("Cannot divide
by zero:", e) finally: print("Done")
8. File Handling
with open("[Link]", "r") as f: content = [Link]() with open("[Link]",
"w") as f: [Link]("Hello, file!")
Using 'with' guarantees the file is closed automatically, even if an exception occurs inside the block.
9. Common Standard Library Modules
Module Purpose
os Interact with the operating system: paths, environment variables, directories
sys Interpreter-level control: command-line args, exit codes
json Parse and write JSON data
re Regular expressions for pattern matching in strings
datetime Work with dates and times
collections Specialized containers: Counter, defaultdict, deque
itertools Efficient looping tools: combinations, permutations, chain
10. Pythonic Idioms Worth Knowing
• Use enumerate() instead of range(len(list)) when you need both index and value.
• Use zip() to iterate over multiple lists in parallel.
• Prefer f-strings (f"{x}") over .format() or % formatting for readability.
• Unpack values directly: a, b = b, a swaps two variables without a temp variable.
• Use context managers (with) for anything that needs cleanup — files, network connections, locks.