PYTHON QUICK REFERENCE CHEATSHEET
================================
=== DATA TYPES ===
str = "text" # String
int = 42 # Integer
float = 3.14 # Float
bool = True # Boolean
list = [1,2,3] # List
dict = {"a":1} # Dictionary
tuple = (1,2,3) # Tuple
set = {1,2,3} # Set
=== STRING METHODS ===
s.upper() # UPPERCASE
s.lower() # lowercase
s.strip() # Remove whitespace
s.split(',') # Split by delimiter
s.replace('a','b') # Replace substring
s.startswith('abc') # Check prefix
s.endswith('xyz') # Check suffix
len(s) # String length
=== LIST METHODS ===
lst.append(item) # Add to end
lst.insert(0, item) # Insert at index
lst.remove(item) # Remove first match
lst.pop() # Remove last item
lst.sort() # Sort in place
lst.reverse() # Reverse in place
len(lst) # List length
=== DICTIONARY METHODS ===
d.keys() # Get all keys
d.values() # Get all values
d.items() # Get key-value pairs
d.get('key', default) # Safe key access
d.pop('key') # Remove and return
d.update(other_dict) # Merge dictionaries
=== CONTROL FLOW ===
# If statement
if condition:
pass
elif other_condition:
pass
else:
pass
# For loop
for item in iterable:
pass
for i in range(10):
pass
# While loop
while condition:
pass
=== LIST COMPREHENSIONS ===
[x*2 for x in range(10)] # Basic
[x for x in lst if x > 5] # With condition
[x.upper() for x in words] # Transform items
=== FUNCTIONS ===
def function_name(param1, param2=default):
"""Docstring"""
return result
# Lambda functions
lambda x: x * 2
map(lambda x: x*2, [1,2,3])
filter(lambda x: x > 0, numbers)
=== FILE OPERATIONS ===
with open('file.txt', 'r') as f:
content = f.read()
with open('file.txt', 'w') as f:
f.write('text')
# File modes: 'r'(read), 'w'(write), 'a'(append), 'rb'(binary read)
=== ERROR HANDLING ===
try:
risky_code()
except SpecificError as e:
handle_error(e)
except Exception as e:
handle_any_error(e)
finally:
cleanup_code()
=== COMMON BUILT-INS ===
len(obj) # Length
max(iterable) # Maximum value
min(iterable) # Minimum value
sum(numbers) # Sum of numbers
sorted(iterable) # Return sorted copy
enumerate(iterable) # Index and value pairs
zip(iter1, iter2) # Combine iterables
range(start, stop, step) # Number sequence
=== STRING FORMATTING ===
f"Hello {name}" # f-strings (Python 3.6+)
"Hello {}".format(name) # .format() method
"Hello %s" % name # % formatting (legacy)
=== USEFUL IMPORTS ===
import os # Operating system interface
import sys # System-specific parameters
import json # JSON encoder/decoder
import datetime # Date and time handling
import random # Generate random numbers
import re # Regular expressions
from collections import defaultdict, Counter
=== CLASS BASICS ===
class MyClass:
def __init__(self, param):
self.attribute = param
def method(self):
return self.attribute
obj = MyClass("value")
result = obj.method()
=== VIRTUAL ENVIRONMENTS ===
python -m venv venv # Create virtual environment
source venv/bin/activate # Activate (Linux/Mac)
venv\Scripts\activate # Activate (Windows)
pip install package_name # Install package
pip freeze > requirements.txt # Export dependencies
pip install -r requirements.txt # Install from file
deactivate # Deactivate environment