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 ===
[Link]() # UPPERCASE
[Link]() # lowercase
[Link]() # Remove whitespace
[Link](',') # Split by delimiter
[Link]('a','b') # Replace substring
[Link]('abc') # Check prefix
[Link]('xyz') # Check suffix
len(s) # String length
=== LIST METHODS ===
[Link](item) # Add to end
[Link](0, item) # Insert at index
[Link](item) # Remove first match
[Link]() # Remove last item
[Link]() # Sort in place
[Link]() # Reverse in place
len(lst) # List length
=== DICTIONARY METHODS ===
[Link]() # Get all keys
[Link]() # Get all values
[Link]() # Get key-value pairs
[Link]('key', default) # Safe key access
[Link]('key') # Remove and return
[Link](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
[[Link]() 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('[Link]', 'r') as f:
content = [Link]()
with open('[Link]', 'w') as f:
[Link]('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):
[Link] = param
def method(self):
return [Link]
obj = MyClass("value")
result = [Link]()
=== 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 > [Link] # Export dependencies
pip install -r [Link] # Install from file
deactivate # Deactivate environment