← Back to Home

Python Quick Reference

Python Quick Reference

Comprehensive Python reference covering syntax, built-in functions, data structures, and common programming patterns. Perfect for quick lookups during development.

Getting Started

This reference assumes basic programming knowledge. Examples use Python 3.8+ syntax. Run code examples in the Python REPL, Jupyter, or your favorite IDE.

Version: Python 3.8+ | Style: PEP 8 compliant

Basic Syntax

Python fundamentals including variables, data types, and basic operations.

Variables & Data Types

Variable Assignment

# Variable assignment
name = "John"
age = 25
is_student = True
# Multiple assignment
x, y, z = 1, 2, 3
a = b = c = 0
# Swapping variables
a, b = b, a

Basic Data Types

# Numbers
integer = 42
float_num = 3.14
complex_num = 3 + 4j
# Strings
single_quote = 'Hello'
double_quote = "World"
multiline = """
This is a
multiline string
"""
# Boolean
is_true = True
is_false = False
# None (null value)
empty_value = None

Type Checking & Conversion

# Check type
type(42) # <class 'int'>
isinstance(42, int) # True
# Type conversion
int("123") # 123
float("3.14") # 3.14
str(42) # "42"
bool(1) # True
bool(0) # False
# String to list
list("hello") # ['h', 'e', 'l', 'l', 'o']

Operators

Arithmetic Operators

a + b # Addition
a - b # Subtraction
a * b # Multiplication
a / b # Division (float result)
a // b # Floor division (integer result)
a % b # Modulo (remainder)
a ** b # Exponentiation
# Compound assignment
a += 1 # Same as a = a + 1
a -= 1 # Same as a = a - 1
a *= 2 # Same as a = a * 2

Comparison & Logical Operators

# Comparison
a == b # Equal
a != b # Not equal
a < b # Less than
a > b # Greater than
a <= b # Less than or equal
a >= b # Greater than or equal
# Logical
a and b # Logical AND
a or b # Logical OR
not a # Logical NOT
# Membership
item in collection
item not in collection
# Identity
a is b # Same object
a is not b # Different objects

Control Flow

Control structures for making decisions and repeating operations.

Conditionals

If Statements

# Basic if statement
if condition:
# do something
pass
# If-else
if age >= 18:
print("Adult")
else:
print("Minor")
# If-elif-else
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"

Ternary Operator

# Ternary operator (conditional expression)
result = "positive" if x > 0 else "negative"
# Chained ternary
result = "positive" if x > 0 else "zero" if x == 0 else "negative"
# With function calls
action = process_data() if data_exists else get_default()

Loops

For Loops

# Basic for loop
for item in [1, 2, 3, 4, 5]:
print(item)
# Range function
for i in range(5): # 0 to 4
print(i)
for i in range(1, 6): # 1 to 5
print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i)
# Enumerate (index and value)
for index, value in enumerate(['a', 'b', 'c']):
print(f"{index}: {value}")
# Zip (parallel iteration)
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")

While Loops

# Basic while loop
i = 0
while i < 5:
print(i)
i += 1
# While with else (executes if loop completes)
i = 0
while i < 3:
print(i)
i += 1
else:
print("Loop completed")

Loop Control

# Break (exit loop)
for i in range(10):
if i == 5:
break
print(i) # Prints 0, 1, 2, 3, 4
# Continue (skip iteration)
for i in range(5):
if i == 2:
continue
print(i) # Prints 0, 1, 3, 4
# Pass (placeholder)
for i in range(3):
if i == 1:
pass # Do nothing
print(i)

Data Structures

Python's built-in data structures for organizing and manipulating data efficiently.

Lists

List Creation & Access

# Creating lists
empty_list = []
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
nested = [[1, 2], [3, 4], [5, 6]]
# List comprehension
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
evens = [x for x in range(10) if x % 2 == 0]
# Accessing elements
first = numbers[0] # First element
last = numbers[-1] # Last element
second_last = numbers[-2] # Second to last

List Methods

# Adding elements
lst.append(item) # Add to end
lst.insert(index, item) # Insert at index
lst.extend([1, 2, 3]) # Add multiple items
# Removing elements
lst.remove(item) # Remove first occurrence
item = lst.pop() # Remove and return last item
item = lst.pop(index) # Remove and return item at index
del lst[index] # Delete item at index
lst.clear() # Remove all items
# Other operations
lst.reverse() # Reverse in place
lst.sort() # Sort in place
count = lst.count(item) # Count occurrences
index = lst.index(item) # Find index of item

List Slicing

lst = [0, 1, 2, 3, 4, 5]
# Basic slicing
lst[1:4] # [1, 2, 3] (start:end)
lst[:3] # [0, 1, 2] (beginning to index)
lst[2:] # [2, 3, 4, 5] (index to end)
lst[:] # [0, 1, 2, 3, 4, 5] (copy)
# Step slicing
lst[::2] # [0, 2, 4] (every 2nd element)
lst[1::2] # [1, 3, 5] (every 2nd, starting at 1)
lst[::-1] # [5, 4, 3, 2, 1, 0] (reverse)
# Negative indices
lst[-3:] # [3, 4, 5] (last 3 elements)
lst[:-2] # [0, 1, 2, 3] (all but last 2)

Dictionaries

Dictionary Creation & Access

# Creating dictionaries
empty_dict = {}
person = {"name": "Alice", "age": 30, "city": "New York"}
dict_from_keys = dict.fromkeys(['a', 'b', 'c'], 0)
# Dictionary comprehension
squares = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Accessing values
name = person["name"] # Direct access
age = person.get("age") # Safe access
city = person.get("city", "Unknown") # With default

Dictionary Methods

# Adding/updating
person["email"] = "alice@email.com" # Add new key
person["age"] = 31 # Update existing
person.update({"phone": "123-456-7890"}) # Update multiple
# Removing
del person["age"] # Remove key
email = person.pop("email") # Remove and return
item = person.popitem() # Remove and return last item
person.clear() # Remove all items
# Iteration
for key in person:
print(key)
for key, value in person.items():
print(f"{key}: {value}")
for value in person.values():
print(value)

Sets & Tuples

Sets (Unique Collections)

# Creating sets
empty_set = set()
numbers = {1, 2, 3, 4, 5}
from_list = set([1, 2, 2, 3, 3]) # {1, 2, 3}
# Set operations
set1.add(item) # Add element
set1.remove(item) # Remove (raises error if not found)
set1.discard(item) # Remove (no error if not found)
# Set mathematics
union = set1 | set2 # Union
intersection = set1 & set2 # Intersection
difference = set1 - set2 # Difference
sym_diff = set1 ^ set2 # Symmetric difference

Tuples (Immutable Sequences)

# Creating tuples
empty_tuple = ()
single_item = (42,) # Note the comma
coordinates = (10, 20)
person = ("Alice", 30, "Engineer")
# Tuple unpacking
name, age, job = person # Unpack all values
x, y = coordinates # Unpack coordinates
first, *rest = (1, 2, 3, 4) # first=1, rest=[2, 3, 4]
# Named tuples
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x, p.y) # 10 20

Functions

Organize code into reusable blocks with parameters, return values, and advanced features.

Function Basics

Function Definition

# Basic function
def greet(name):
return f"Hello, {name}!"
# Function with default parameters
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
# Function with multiple return values
def get_name_age():
return "Alice", 30
name, age = get_name_age() # Tuple unpacking
# Function with docstring
def calculate_area(radius):
"""Calculate the area of a circle.
Args:
radius (float): The radius of the circle
Returns:
float: The area of the circle
"""
return 3.14159 * radius ** 2

Function Arguments

# Positional and keyword arguments
def create_profile(name, age, city="Unknown", active=True):
return {"name": name, "age": age, "city": city, "active": active}
# Calling with different argument styles
profile1 = create_profile("Alice", 30)
profile2 = create_profile("Bob", age=25, city="Boston")
profile3 = create_profile(city="Chicago", name="Carol", age=35)
# *args and **kwargs
def flexible_function(*args, **kwargs):
print("Positional args:", args)
print("Keyword args:", kwargs)
flexible_function(1, 2, 3, name="Alice", age=30)
# Output:
# Positional args: (1, 2, 3)
# Keyword args: {'name': 'Alice', 'age': 30}

Advanced Functions

Lambda Functions

# Basic lambda
square = lambda x: x ** 2
print(square(5)) # 25
# Lambda with multiple arguments
add = lambda x, y: x + y
print(add(3, 4)) # 7
# Using lambda with built-in functions
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
evens = list(filter(lambda x: x % 2 == 0, numbers))
# Sorting with lambda
students = [('Alice', 85), ('Bob', 90), ('Charlie', 78)]
students.sort(key=lambda x: x[1]) # Sort by grade

Decorators

# Simple decorator
def timer(func):
def wrapper(*args, **kwargs):
import time
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Execution time: {end - start:.4f}s")
return result
return wrapper
# Using decorator
@timer
def slow_function():
time.sleep(1)
return "Done"

Generators

# Generator function
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
# Using generator
for num in fibonacci(10):
print(num, end=" ") # 0 1 1 2 3 5 8 13 21 34
# Generator expression
squares = (x**2 for x in range(10))
print(list(squares)) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Classes & OOP

Object-oriented programming with classes, inheritance, and special methods.

Class Basics

Class Definition

# Basic class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, I'm {self.name}"
def birthday(self):
self.age += 1
return f"Happy birthday! Now {self.age} years old"
# Creating and using objects
person = Person("Alice", 30)
print(person.greet()) # Hello, I'm Alice
print(person.birthday()) # Happy birthday! Now 31 years old

Special Methods

class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __str__(self):
return f"{self.title} ({self.pages} pages)"
def __repr__(self):
return f"Book('{self.title}', {self.pages})"
def __len__(self):
return self.pages
def __eq__(self, other):
return self.pages == other.pages
# Using special methods
book = Book("Python Guide", 200)
print(book) # Python Guide (200 pages)
print(len(book)) # 200

Inheritance

Basic Inheritance

# Parent class
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def speak(self):
return f"{self.name} makes a sound"
# Child class
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name, "Canine")
self.breed = breed
def speak(self): # Override parent method
return f"{self.name} barks"
def fetch(self): # New method
return f"{self.name} fetches the ball"
# Using inheritance
dog = Dog("Buddy", "Golden Retriever")
print(dog.speak()) # Buddy barks
print(dog.fetch()) # Buddy fetches the ball

Modules & Packages

Importing Modules

# Different import styles
import math
print(math.pi) # 3.141592653589793
import math as m
print(m.sqrt(16)) # 4.0
from math import pi, sqrt
print(pi) # 3.141592653589793
print(sqrt(25)) # 5.0
from math import * # Import all (not recommended)
# Creating your own module (save as mymodule.py)
def greet(name):
return f"Hello, {name}!"
PI = 3.14159
# Using your module
import mymodule
print(mymodule.greet("Alice"))
print(mymodule.PI)

File I/O

Reading and Writing Files

# Writing to a file
with open('example.txt', 'w') as file:
file.write("Hello, World!")
file.write("\\nSecond line")
# Reading from a file
with open('example.txt', 'r') as file:
content = file.read() # Read entire file
print(content)
# Reading line by line
with open('example.txt', 'r') as file:
for line in file:
print(line.strip()) # Remove newline characters
# Appending to a file
with open('example.txt', 'a') as file:
file.write("\\nAppended line")
# Working with CSV files
import csv
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['Alice', 30, 'New York'])

Error Handling

Try-Except Blocks

# Basic exception handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
# Multiple exception types
try:
number = int(input("Enter a number: "))
result = 10 / number
except ValueError:
print("Invalid input! Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"An error occurred: {e}")
else:
print(f"Result: {result}")
finally:
print("This always executes")

Raising Exceptions

# Raising custom exceptions
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
if age > 150:
raise ValueError("Age seems unrealistic")
return age
# Custom exception class
class CustomError(Exception):
pass
def risky_function():
raise CustomError("Something went wrong")

Built-in Functions

Essential Built-ins

# Mathematical functions
abs(-5) # 5 (absolute value)
min(1, 2, 3) # 1
max(1, 2, 3) # 3
sum([1, 2, 3]) # 6
round(3.14159, 2) # 3.14
# Type conversion
int("123") # 123
float("3.14") # 3.14
str(123) # "123"
bool(1) # True
# Sequence functions
len([1, 2, 3]) # 3
sorted([3, 1, 2]) # [1, 2, 3]
reversed([1, 2, 3]) # <reversed object>
list(reversed([1, 2, 3])) # [3, 2, 1]
# Functional programming
map(str, [1, 2, 3]) # <map object>
list(map(str, [1, 2, 3])) # ['1', '2', '3']
filter(lambda x: x > 2, [1, 2, 3, 4]) # <filter object>
list(filter(lambda x: x > 2, [1, 2, 3, 4])) # [3, 4]

Input/Output & Inspection

# Input/Output
name = input("Enter your name: ")
print("Hello,", name)
print("Value:", 42, "Type:", type(42))
# Object inspection
dir(list) # List all methods of list
help(len) # Get help for len function
hasattr(obj, 'method') # Check if object has attribute
getattr(obj, 'attr', 'default') # Get attribute safely
isinstance(42, int) # True
# Variable management
globals() # Global variables
locals() # Local variables
vars(obj) # Object's attributes as dict

Common Libraries

Standard Library Highlights

# datetime - Working with dates and times
from datetime import datetime, date, timedelta
now = datetime.now()
today = date.today()
tomorrow = today + timedelta(days=1)
# os - Operating system interface
import os
os.getcwd() # Current directory
os.listdir('.') # List directory contents
os.path.join('path', 'to', 'file') # Path joining
# random - Generate random numbers
import random
random.randint(1, 10) # Random integer
random.choice([1, 2, 3]) # Random choice
random.shuffle(my_list) # Shuffle list in place
# json - JSON encoder/decoder
import json
data = {"name": "Alice", "age": 30}
json_string = json.dumps(data) # Dict to JSON
parsed_data = json.loads(json_string) # JSON to dict

Popular Third-Party Libraries

# requests - HTTP library
import requests
response = requests.get('https://api.github.com/users/octocat')
data = response.json()
# pandas - Data manipulation
import pandas as pd
df = pd.read_csv('data.csv')
df.head() # Show first 5 rows
# numpy - Numerical computing
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(np.mean(arr)) # Calculate mean
# matplotlib - Plotting
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()

Install third-party libraries using pip: `pip install requests pandas numpy matplotlib`

🐍 Python Best Practices

  • • Follow PEP 8 style guide for consistent code formatting
  • • Use descriptive variable and function names
  • • Write docstrings for functions and classes
  • • Handle exceptions appropriately with try-except blocks
  • • Use list comprehensions for simple transformations
  • • Prefer `with` statements for file operations
  • • Use virtual environments for project dependencies

🚀 Keep Practicing

This cheatsheet covers Python fundamentals and common patterns. Practice these concepts by building small projects and solving coding challenges. The more you code, the more natural these patterns will become.