Ultimate Python Cheat Sheet Guide
Ultimate Python Cheat Sheet Guide
Get unlimited access to the best of Medium for less than $1/week. Become a member
[Link] 1/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
This Cheat Sheet was born out of necessity. Recently, I was tasked with diving into a
new Python project after some time away from the language.
I’ve always appreciated Python’s practical syntax and form. However, being in
Node/Typescript land for some time, I found myself in need of a rapid refresher on
Python’s latest features, best practices, and most impactful tools. I needed to get
back up to speed quickly without getting bogged down in the minutiae so I compiled
this list so that I could reference the tasks and features I needed to use the most
often. Essentially, to grasp the essential 20% of Python that addresses 80% of the
programming needs I would encounter.
[Link] 2/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
This guide is the culmination of that journey, offering a collection of the most
practical Python knowledge, insights, and useful libraries that I encountered along
the way. It’s designed to share my learning that I found most valuable, presented in a
way that’s immediately applicable to your projects and challenges.
I’ve broken up the sections into logical areas that typically work together so that you
can jump to an area you are interested in and find the most related items to that
particular task or subject. This will include file operations, API interactions,
spreadsheet manipulation, mathematical computations, and working with data
structures like lists and dictionaries. Additionally, I’ll highlight some useful libraries
to enhance your Python toolkit that are prevalent in the domains Python is typically
used.
Open inbe
If you think I missed anything that should appincluded in the Cheat Sheet, please let
💡 You might also find this pandas cheatsheet useful if you need to perform some quick
data analysis:
1. Reading a File
To read the entire content of a file:
2. Writing to a File
To write text to a file, overwriting existing content:
[Link] 3/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
3. Appending to a File
To add text to the end of an existing file:
import os
if [Link]('[Link]'):
print('File exists.')
[Link] 4/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
else:
print('File does not exist.')
9. Deleting a File
To safely delete a file if it exists:
import os
if [Link]('[Link]'):
[Link]('[Link]')
print('File deleted.')
else:
print('File does not exist.')
[Link] 5/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
import requests
response = [Link]('[Link]
data = [Link]() # Assuming the response is JSON
print(data)
import requests
params = {'key1': 'value1', 'key2': 'value2'}
response = [Link]('[Link] params=params)
data = [Link]()
print(data)
import requests
response = [Link]('[Link]
try:
response.raise_for_status() # Raises an HTTPError if the status is 4xx, 5x
data = [Link]()
print(data)
[Link] 6/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
import requests
try:
response = [Link]('[Link] timeout=5) # Timeo
data = [Link]()
print(data)
except [Link]:
print('The request timed out')
import requests
headers = {'Authorization': 'Bearer YOUR_ACCESS_TOKEN'}
response = [Link]('[Link] headers=headers)
data = [Link]()
print(data)
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
headers = {'Content-Type': 'application/json'}
response = [Link]('[Link] json=payload, header
print([Link]())
import requests
response = [Link]('[Link]
[Link] = 'utf-8' # Set encoding to match the expected response form
data = [Link]
print(data)
import requests
with [Link]() as session:
[Link]({'Authorization': 'Bearer YOUR_ACCESS_TOKEN'})
response = [Link]('[Link]
print([Link]())
9. Handling Redirects
To handle or disable redirects in requests:
import requests
response = [Link]('[Link] allow_redirects=False)
print(response.status_code)
import requests
response = [Link]('[Link] stream=True)
[Link] 8/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
1. Creating a List
To conjure a list into being:
2. Appending to a List
To append a new element to the end of a list:
[Link]('Aether')
[Link] 9/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
index_of_air = [Link]('Air')
7. List Slicing
To slice a list, obtaining a sub-list:
8. List Comprehension
To create a new list by applying an expression to each element of an existing one:
9. Sorting a List
To sort a list in ascending order (in-place):
[Link]()
[Link] 10/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
[Link]()
1. Creating a Dictionary
To forge a new dictionary:
3. Removing an Entry
To banish an entry from the dictionary:
if 'Helium' in elements:
print('Helium is present')
[Link] 11/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
8. Dictionary Comprehension
To conjure a new dictionary through an incantation over an iterable:
9. Merging Dictionaries
To merge two or more dictionaries, forming a new alliance of their entries:
[Link] 12/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
import os
# Craft a path compatible with the underlying OS
path = [Link]('mystic', 'forest', '[Link]')
# Retrieve the tome's directory
directory = [Link](path)
# Unveil the artifact's name
artifact_name = [Link](path)
import os
contents = [Link]('enchanted_grove')
print(contents)
3. Creating Directories
To conjure new directories within the fabric of the filesystem:
import os
# create a single directory
[Link]('alchemy_lab')
# create a hierarchy of directories
[Link]('alchemy_lab/potions/elixirs')
[Link] 13/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
import os
# remove a file
[Link]('unnecessary_scroll.txt')
# remove an empty directory
[Link]('abandoned_hut')
# remove a directory and its contents
import shutil
[Link]('cursed_cavern')
import subprocess
# Invoke the 'echo' incantation
result = [Link](['echo', 'Revealing the arcane'], capture_output=True,
print([Link])
import os
# Read the 'PATH' variable
path = [Link]('PATH')
# Create a new environment variable
[Link]['MAGIC'] = 'Arcane'
import os
# Traverse to the 'arcane_library' directory
[Link] 14/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
[Link]('arcane_library')
import os
# Check if a path exists
exists = [Link]('mysterious_ruins')
# Ascertain if the path is a directory
is_directory = [Link]('mysterious_ruins')
# Determine if the path is a file
is_file = [Link]('ancient_manuscript.txt')
import tempfile
# Create a temporary file
temp_file = [Link](delete=False)
print(temp_file.name)
# Erect a temporary directory
temp_dir = [Link]()
print(temp_dir.name)
import os
import platform
# Discover the operating system
os_name = [Link] # 'posix', 'nt', 'java'
# Unearth detailed system information
system_info = [Link]() # 'Linux', 'Windows', 'Darwin'
2. Printing to STDOUT
To print messages to the console:
3. Formatted Printing
To weave variables into your messages with grace and precision:
name = "Merlin"
age = 300
print(f"{name}, of {age} years, speaks of forgotten lore.")
import sys
for line in [Link]:
print(f"Echo from the void: {[Link]()}")
5. Writing to STDERR
To send message to STDERR:
import sys
[Link] 16/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
6. Redirecting STDOUT
To redirect the STDOUT:
import sys
original_stdout = [Link] # Preserve the original STDOUT
with open('mystic_log.txt', 'w') as f:
[Link] = f # Redirect STDOUT to a file
print("This message is inscribed within the mystic_log.txt.")
[Link] = original_stdout # Restore STDOUT to its original glory
7. Redirecting STDERR
Redirecting STDERR:
import sys
with open('[Link]', 'w') as f:
[Link] = f # Redirect STDERR
print("This warning is sealed within [Link].", file=[Link])
import getpass
secret_spell = [Link]("Whisper the secret spell: ")
import sys
# The script's name is the first argument, followed by those passed by the invo
[Link] 17/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
import argparse
parser = [Link](description="Invoke the ancient scripts.")
parser.add_argument('spell', help="The spell to cast")
parser.add_argument('--power', type=int, help="The power level of the spell")
args = parser.parse_args()
print(f"Casting {[Link]} with power {[Link]}")
sum = 7 + 3 # Addition
difference = 7 - 3 # Subtraction
product = 7 * 3 # Multiplication
quotient = 7 / 3 # Division
remainder = 7 % 3 # Modulus (Remainder)
power = 7 ** 3 # Exponentiation
3. Mathematical Functions
[Link] 18/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
import math
root = [Link](16) # Square root
logarithm = [Link](100, 10) # Logarithm base 10 of 100
sine = [Link]([Link] / 2) # Sine of 90 degrees (in radians)
4. Generating Permutations
Easy way to generate permutations from a given set:
5. Generating Combinations
Easy way to generate combinations:
import random
num = [Link](1, 100) # Generate a random integer between 1 and 100
[Link] 19/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
8. Statistical Functions
To get Average, Median, and Standard Deviation:
import statistics
data = [1, 2, 3, 4, 5]
mean = [Link](data) # Average
median = [Link](data) # Median
stdev = [Link](data) # Standard Deviation
9. Trigonometric Functions
To work with trigonometry:
import math
angle_rad = [Link](60) # Convert 60 degrees to radians
cosine = [Link](angle_rad) # Cosine of the angle
import math
infinity = [Link] # Representing infinity
not_a_number = [Link] # Representing a non-number (NaN)
1. Establishing a Connection
To create a connection to a Postgres Database:
[Link] 20/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
import psycopg2
connection = [Link](
dbname='your_database',
user='your_username',
password='your_password',
host='your_host'
)
2. Creating a Cursor
To create a database cursor, enabling the traversal and manipulation of records:
cursor = [Link]()
3. Executing a Query
Selecting data from Database:
records = [Link]()
for record in records:
print(record)
5. Inserting Records
To insert data into tables in a database:
[Link] 21/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
6. Updating Records
To alter the records:
7. Deleting Records
To delete records from the table:
8. Creating a Table
To create a new table, defining its structure:
[Link]("""
CREATE TABLE your_new_table (
id SERIAL PRIMARY KEY,
column1 VARCHAR(255),
column2 INTEGER
)
""")
[Link]()
9. Dropping a Table
To drop a table:
[Link] 22/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
[Link]()
try:
[Link]("your first transactional query")
[Link]("your second transactional query")
[Link]() # Commit if all is well
except Exception as e:
[Link]() # Rollback in case of any issue
print(f"An error occurred: {e}")
import asyncio
async def fetch_data():
print("Fetching data...")
await [Link](2) # Simulate an I/O operation
print("Data retrieved.")
[Link] 23/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
4. Creating Tasks
To dispatch tasks:
5. Asynchronous Iteration
To traverse through asynchronously, allowing time for other functions in between:
print("Within context")
[Link](main())
8. Asynchronous Generators
To create async generators, each arriving in its own time:
9. Using Semaphores
To limit the number of concurrent tasks:
[Link] 25/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
1. Creating a Socket
To create a socket for network communication:
import socket
s = [Link](socket.AF_INET, socket.SOCK_STREAM)
3. Sending Data
To dispatch data through the network to a connected entity:
[Link] 26/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
[Link](b'Hello, server')
4. Receiving Data
To receive data from the network:
5. Closing a Socket
To gracefully close the socket, severing the network link:
[Link]()
7. Accepting Connections
To accept and establish a network link:
[Link] 27/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
[Link](False)
import socket
import netifaces
for interface in [Link]():
addr = [Link](interface).get(netifaces.AF_INET)
if addr:
print(f"Interface: {interface}, Address: {addr[0]['addr']}")
1. Creating a DataFrame
To create a DataFrame with your own columns and data:
import pandas as pd
data = {
'Element': ['Earth', 'Water', 'Fire', 'Air'],
'Symbol': ['🜃', '🜄', '🜂', '🜁']
}
df = [Link](data)
df = pd.read_csv('[Link]')
print([Link]())
4. Selecting Columns
To select specific columns from dataframe:
symbols = df['Symbol']
5. Filtering Rows
To sift through the DataFrame, selecting rows that meet your criteria:
df['Length'] = df['Element'].apply(len)
[Link] 29/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
8. Merging DataFrames
To weave together two DataFrames, joining them by a shared key:
[Link](value='Unknown', inplace=True)
import numpy as np
array = [Link]([1, 2, 3, 4, 5])
5. Reshaping an Array
To transmute the shape of an array, altering its dimensions:
a = [Link]([1, 2, 3])
b = [Link]([4, 5, 6])
sum = a + b # Element-wise addition
difference = b - a # Element-wise subtraction
product = a * b # Element-wise multiplication
[Link] 31/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
7. Matrix Multiplication
Basic dot product Operation:
9. Boolean Indexing
To filter the elements of an array through the sieve of conditionals:
mean = [Link](a)
maximum = [Link](a)
sum = [Link](a)
[Link] 32/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
[Link](x, y)
[Link]('Growth Over Time')
[Link]('Time')
[Link]('Growth')
[Link]()
[Link](x, y)
[Link]()
z = [2, 3, 4, 5, 6]
[Link](x, y)
[Link] 33/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
[Link](x, z)
[Link]()
6. Creating Subplots
To create subplots:
7. Creating a Histogram
To create a histogram:
data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
[Link](data, bins=4)
[Link]()
8. Adding a Legend
To create a legend for the plot:
[Link](x, y, label='Growth')
[Link](x, z, label='Decay')
[Link]()
[Link]()
9. Customizing Ticks
To create your own marks upon the axes, defining the scale of your values:
[Link](x, y)
[Link]([1, 2, 3, 4, 5], ['One', 'Two', 'Three', 'Four', 'Five'])
[Link] 34/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
[Link]([0, 5, 10, 15, 20, 25], ['0', '5', '10', '15', '20', '25+'])
[Link]()
[Link](x, y)
[Link]('growth_over_time.png')
1. Loading a Dataset
To work with datasets for your ML experiments
3. Training a Model
Training a ML Model using RandomForestClassifier:
[Link] 35/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
4. Making Predictions
To access the model predictions:
predictions = [Link](X_test)
6. Using Cross-Validation
To use Cross-Validation:
7. Feature Scaling
To create the appropriate scales of your features, allowing the model to learn more
effectively:
[Link] 36/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
9. Pipeline Creation
To streamline your data processing and modeling steps, crafting a seamless flow:
import joblib
# Saving the model
[Link](model, '[Link]')
# Loading the model
loaded_model = [Link]('[Link]')
import plotly.graph_objs as go
import [Link] as pio
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
fig = [Link](data=[Link](x=x, y=y, mode='lines'))
[Link](fig)
[Link] 37/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
5. Creating a Histogram
To create a Histogram:
data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
fig = [Link](data=[Link](x=data))
[Link](fig)
[Link] 38/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
data = [1, 2, 2, 3, 4, 4, 4, 5, 5, 6]
fig = [Link](data=[Link](y=data))
[Link](fig)
7. Creating Heatmaps
To create a heatmap:
import numpy as np
z = [Link](10, 10) # Generate random data
fig = [Link](data=[Link](z=z))
[Link](fig)
9. Creating Subplots
To create a subplot:
[Link] 39/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
import pandas as pd
dates = pd.date_range('20230101', periods=5)
values = [10, 11, 12, 13, 14]
fig = [Link](data=[Link](x=dates, y=values, mode='lines+markers'))
[Link](fig)
year = [Link]
month = [Link]
day = [Link]
hour = [Link]
minute = [Link]
second = [Link]
print(f"Year: {year}, Month: {month}, Day: {day}, Hour: {hour}, Minute: {minute
[Link] 41/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
weekday = [Link]("%A")
print(f"Today is: {weekday}")
timestamp = [Link](now)
print(f"Current timestamp: {timestamp}")
# Converting a timestamp back to a datetime
date_from_timestamp = [Link](timestamp)
print(f"Date from timestamp: {date_from_timestamp}")
[Link] 42/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
[Link] 43/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
import math
transformed = [[Link](x) for x in range(1, 6)]
print(transformed) # Square roots of numbers from 1 to 5
[Link] 44/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
1. Defining a Class
Creating a class:
class Wizard:
def __init__(self, name, power):
[Link] = name
[Link] = power
def cast_spell(self):
print(f"{[Link]} casts a spell with power {[Link]}!")
2. Creating an Instance
To create an instance of your class:
3. Invoking Methods
To call methods on instance of class:
merlin.cast_spell()
4. Inheritance
Subclassing:
class ArchWizard(Wizard):
def __init__(self, name, power, realm):
super().__init__(name, power)
[Link] 45/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
[Link] = realm
def summon_familiar(self):
print(f"{[Link]} summons a familiar from the {[Link]} realm.")
5. Overriding Methods
To overide base classes:
class Sorcerer(Wizard):
def cast_spell(self):
print(f"{[Link]} casts a powerful dark spell!")
6. Polymorphism
To interact with different forms through a common interface:
def unleash_magic(wizard):
wizard.cast_spell()
unleash_magic(merlin)
unleash_magic(Sorcerer("Voldemort", 90))
7. Encapsulation
To use information hiding:
class Alchemist:
def __init__(self, secret_ingredient):
self.__secret = secret_ingredient
def reveal_secret(self):
print(f"The secret ingredient is {self.__secret}")
8. Composition
To assemble Objects from simpler ones:
[Link] 46/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
class Spellbook:
def __init__(self, spells):
[Link] = spells
class Mage:
def __init__(self, name, spellbook):
[Link] = name
[Link] = spellbook
class Enchanter:
@staticmethod
def enchant(item):
print(f"{item} is enchanted!")
@classmethod
def summon(cls):
print("A new enchanter is summoned.")
class Elementalist:
def __init__(self, element):
self._element = element
@property
def element(self):
return self._element
@[Link]
def element(self, value):
if value in ["Fire", "Water", "Earth", "Air"]:
self._element = value
else:
print("Invalid element!")
[Link] 47/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
1. Basic Decorator
To create a simple decorator that wraps a function:
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before call")
result = func(*args, **kwargs)
print("After call")
return result
return wrapper
@my_decorator
def greet(name):
print(f"Hello {name}")
greet("Alice")
3. Using [Link]
To preserve the metadata of the original function when decorating:
def my_decorator(func):
@wraps(func)
[Link] 48/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
@my_decorator
def greet(name):
"""Greet someone"""
print(f"Hello {name}")
4. Class Decorator
To create a decorator using a class:
class MyDecorator:
def __init__(self, func):
[Link] = func
def __call__(self, *args, **kwargs):
print("Before call")
[Link](*args, **kwargs)
print("After call")
@MyDecorator
def greet(name):
print(f"Hello {name}")
greet("Alice")
def repeat(times):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for _ in range(times):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
[Link] 49/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
def say_hello():
print("Hello")
say_hello()
6. Method Decorator
To apply a decorator to a method within a class:
def method_decorator(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
print("Method Decorator")
return func(self, *args, **kwargs)
return wrapper
class MyClass:
@method_decorator
def greet(self, name):
print(f"Hello {name}")
obj = MyClass()
[Link]("Alice")
7. Stacking Decorators
To apply multiple decorators to a single function:
@my_decorator
@repeat(2)
def greet(name):
print(f"Hello {name}")
greet("Alice")
def smart_decorator(arg=None):
def decorator(func):
[Link] 50/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
@wraps(func)
def wrapper(*args, **kwargs):
if arg:
print(f"Argument: {arg}")
return func(*args, **kwargs)
return wrapper
if callable(arg):
return decorator(arg)
return decorator
@smart_decorator
def no_args():
print("No args")
@smart_decorator("With args")
def with_args():
print("With args")
no_args()
with_args()
class MyClass:
@classmethod
@my_decorator
def class_method(cls):
print("Class method called")
MyClass.class_method()
class MyClass:
@staticmethod
@my_decorator
def static_method():
print("Static method called")
MyClass.static_method()
[Link] 51/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
query = gql('''
{
allWizards {
id
name
power
}
}
''')
result = [Link](query)
print(result)
query = gql('''
query GetWizards($element: String!) {
wizards(element: $element) {
id
name
}
}
''')
params = {"element": "Fire"}
[Link] 52/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
4. Mutations
To create and execute a mutation:
mutation = gql('''
mutation CreateWizard($name: String!, $element: String!) {
createWizard(name: $name, element: $element) {
wizard {
id
name
}
}
}
''')
params = {"name": "Gandalf", "element": "Light"}
result = [Link](mutation, variable_values=params)
print(result)
5. Handling Errors
Error handling:
6. Subscriptions
Working with Subscriptions:
subscription = gql('''
subscription {
wizardUpdated {
id
name
[Link] 53/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
power
}
}
''')
for result in [Link](subscription):
print(result)
7. Fragments
Working with Fragments:
query = gql('''
fragment WizardDetails on Wizard {
name
power
}
query {
allWizards {
...WizardDetails
}
}
''')
result = [Link](query)
print(result)
8. Inline Fragments
To tailor the response based on the type of the object returned:
query = gql('''
{
search(text: "magic") {
__typename
... on Wizard {
name
power
}
... on Spell {
name
effect
}
}
}
''')
[Link] 54/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
result = [Link](query)
print(result)
9. Using Directives
To dynamically include or skip fields in your queries based on conditions:
query = gql('''
query GetWizards($withPower: Boolean!) {
allWizards {
name
power @include(if: $withPower)
}
}
''')
params = {"withPower": True}
result = [Link](query, variable_values=params)
print(result)
transport = RequestsHTTPTransport(url='[Link]
client = Client(transport=transport, fetch_schema_from_transport=True)
[Link] 55/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
import re
text = "Search this string for patterns."
match = [Link](r"patterns", text)
if match:
print("Pattern found!")
pattern = [Link](r"patterns")
match = [Link](text)
if [Link](r"^Search", text):
print("Starts with 'Search'")
if [Link](r"patterns.$", text):
print("Ends with 'patterns.'")
[Link] 56/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
print(replaced_text)
6. Splitting a String
To split a string by occurrences of a pattern:
9. Non-Capturing Groups
To define groups without capturing them:
[Link] 57/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
To match a pattern based on what comes before or after it without including it in the
result:
[Link] 58/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
html = "<body><h1>Title</h1></body>"
match = [Link](r"<.*?>", html)
if match:
print([Link]()) # Matches '<body>'
pattern = [Link](r"""
\b # Word boundary
\w+ # One or more word characters
\s # Space
""", [Link])
match = [Link](text)
1. Concatenating Strings
To join strings together:
greeting = "Hello"
name = "Alice"
message = greeting + ", " + name + "!"
print(message)
[Link] 59/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
s = "Python"
print([Link]()) # Uppercase
print([Link]()) # Lowercase
print([Link]()) # Title Case
s = "[Link]"
print([Link]("file")) # True
print([Link](".txt")) # True
[Link] 60/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
s = "split,this,string"
words = [Link](",") # Split string into list
joined = " ".join(words) # Join list into string
print(words)
print(joined)
s = "Hello world"
new_s = [Link]("world", "Python")
print(new_s)
s = "characters"
for char in s:
print(char) # Prints each character on a new line
[Link] 61/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
print("123".isdigit()) # True
print("abc".isalpha()) # True
print("abc123".isalnum())# True
s = "slice me"
sub = s[2:7] # From 3rd to 7th character
print(sub)
s = "length"
print(len(s)) # 6
path = r"C:\User\name\folder"
print(path)
[Link] 62/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
import requests
url = '[Link]
response = [Link](url)
html = [Link]
base_url = "[Link]
for page in range(1, 6): # For 5 pages
page_url = base_url + str(page)
response = [Link](page_url)
# Process each page's content
# Find the URL of the AJAX request (using browser's developer tools) and fetch
ajax_url = '[Link]
data = [Link](ajax_url).json() # Assuming the response is JSON
[Link] 64/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
import re
emails = [Link](r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', htm
rp = RobotFileParser()
rp.set_url('[Link]
[Link]()
can_scrape = rp.can_fetch('*', url)
session = [Link]()
[Link]('[Link]
[Link]('key', 'value') # Set cookies, if needed
response = [Link]('[Link]
try:
response = [Link](url, timeout=5)
response.raise_for_status() # Raises an error for bad status codes
except [Link] as e:
print(f"Error: {e}")
import aiohttp
import asyncio
import csv
1. Installing a Package
To summon a library from the vast repositories, incorporating its power into your
environment:
[Link] 66/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
pip list
3. Upgrading a Package
To imbue an installed library with enhanced powers and capabilities, elevating it to
its latest form:
4. Uninstalling a Package
To uninstall a package:
[Link] 67/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
# On Unix or MacOS
source venv/bin/activate
[Link] 68/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
import os
current_directory = [Link]() # Get the current working directory
import sys
[Link]() # Exit the script
import math
result = [Link](16) # Square root
[Link] 69/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
import random
number = [Link](1, 10) # Random integer between 1 and 10
import json
json_string = [Link]({'name': 'Alice', 'age': 30}) # Dictionary to JSON st
7. re - Regular Expressions
To work with regular expressions:
import re
match = [Link]('Hello', 'Hello, world!') # Search for 'Hello' in the string
[Link] 70/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
[Link](b'<html><head><title>Python HTTP
Server</title></head>')
[Link](b'<body><h1>Hello from a simple Python HTTP
server!</h1></body></html>')
def run(server_class=HTTPServer,
handler_class=SimpleHTTPRequestHandler):
server_address = ('', 8000) # Serve on all addresses, port 8000
httpd = server_class(server_address, handler_class)
print("Server starting on port 8000...")
httpd.serve_forever()
if __name__ == '__main__':
run()
import subprocess
[Link](['ls', '-l']) # Run the 'ls -l' command
import socket
s = [Link](socket.AF_INET, socket.SOCK_STREAM) # Create a TCP/IP socket
import threading
def worker():
[Link] 71/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
import argparse
parser = [Link](description="Process some integers.")
args = parser.parse_args()
import logging
[Link]('This is a warning message')
import unittest
class TestStringMethods([Link]):
[Link] 72/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
def test_upper(self):
[Link]('foo'.upper(), 'FOO')
import itertools
for combination in [Link]('ABCD', 2):
[Link] 73/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
print(combination)
import hashlib
hash_object = hashlib.sha256(b'Hello World')
hex_dig = hash_object.hexdigest()
import csv
with open('[Link]', mode='r') as infile:
reader = [Link](infile)
import [Link] as ET
tree = [Link]('[Link]')
root = [Link]()
import sqlite3
conn = [Link]('[Link]')
[Link] 74/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
import tkinter as tk
root = [Link]()
import pickle
serialized_obj = [Link](obj)
import time
[Link](1) # Sleep for 1 second
import calendar
print([Link](2023, 1)) # Print the calendar for January 2023
[Link] 75/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
import shutil
[Link]('[Link]', '[Link]')
import glob
for file in [Link]("*.txt"):
print(file)
import tempfile
temp = [Link]()
[Link] 76/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
import bz2
compressed = [Link](b'your data here')
import gzip
with [Link]('[Link]', 'wt') as f:
[Link]('your data here')
import ssl
ssl.wrap_socket(sock)
import imaplib
mail = imaplib.IMAP4_SSL('[Link]')
import smtplib
server = [Link]('[Link]', 587)
To manage email messages, including MIME and other RFC 2822-based message
documents:
import base64
encoded_data = base64.b64encode(b'data to encode')
import difflib
diff = [Link]('one\ntwo\nthree\n'.splitlines(keepends=True),
'ore\ntree\nemu\n'.splitlines(keepends=True))
print(''.join(diff))
import gettext
[Link]('myapp')
[Link] 78/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
import locale
[Link](locale.LC_ALL, '')
import secrets
secure_token = secrets.token_hex(16)
import uuid
unique_id = uuid.uuid4()
import html
escaped = [Link]('<a href="[Link]
To work with tar archive files, allowing you to archive and compress/decompress:
import tarfile
with [Link]('[Link]', 'w:gz') as tar:
[Link]('[Link]')
Well, that’s all I have for now. I hope this list helps you get up to speed fast. If you
like it, please share or give it a like (it helps a lot!).
Stackademic 🎓
Thank you for reading until the end. Before you go:
Follow
[Link] 80/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
Published in Stackademic
27K Followers · Last published 4 hours ago
Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free
coding education for the world.
Follow
Responses (56)
Respond
Derek H
11 months ago
I'd suggest always using .get() for dictionary access; it will return a None if you do not give a default. This
means your subsequent code always has data to process. Otherwise you're going to need to wrap the access
in a try-except and handle the KeyError.
56 1 reply Reply
avinash beepath
11 months ago
Wow I am now starting my Python journey and this list is priceless! Thank you!
[Link] 81/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
33 Reply
Mohamed Meeran
11 months ago
It serves as more than just a Python cheat sheet; it is a comprehensive article providing an excellent starting
point to become acquainted with Python.
20 1 reply Reply
[Link] 82/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
Jason Roell
[Link] 83/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
Jason Roell
As someone who uses these tools and models extensively, I aim to unravel the complexities
and nuances of RNNs, Transformers, and Diffusion…
Carlyn Beccia
[Link] 85/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
Mark Manson
Lists
[Link] 86/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
Riikka Iivanainen
The secret life of people with high self-control (it’s easier than you think)
Research suggests that people with high self-control are good at avoiding temptation — not
resisting it
[Link] 87/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
Jessica Stillman
Jeff Bezos Says the 1-Hour Rule Makes Him Smarter. New Neuroscience
Says He’s Right
Jeff Bezos’s morning routine has long included the one-hour rule. New neuroscience says yours
probably should too.
Harendra
[Link] 88/89
1/7/25, 3:29 PM Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks | by Jason Roell | Stackademic
[Link] 89/89
The 'with open' syntax is used in Python to handle files effectively. It ensures that files are properly opened and closed, which is crucial for preventing resource leaks. When using 'with open', the file is automatically closed when the block inside 'with' is exited, even if an exception is raised. This method handles overhead management efficiently in file operations such as writing, appending, and reading files .
The robots.txt file plays a crucial role in ethical web scraping by specifying the rules set by websites regarding which parts can be scraped by web crawlers. In Python, this file can be parsed using the 'urllib.robotparser' module, which allows a scraper to check permissions with 'rp.can_fetch()' before accessing URLs. Ensuring compliance with robots.txt not only respects the website's policies but also helps avoid potential legal issues .
BeautifulSoup is highly beneficial for web scraping due to its ease of use in parsing HTML documents and extracting data. Its methods like parsing with 'soup.find_all()' for finding specific tags, and navigating with '.find()' and '.select()', allow developers to easily traverse the HTML document tree, extract texts or attributes effectively. This library seamlessly handles Unicode and encodings, offering robust functionality for acquiring and manipulating large quantities of HTML content .
Python lists are a versatile data structure allowing various efficient data manipulation operations. Common operations include: appending with 'append()', inserting with 'insert()', removing by value with 'remove()', and getting elements with slicing. For instance, appending a value is done using 'list.append(item)', which adds 'item' to the list end efficiently. These operations make lists suitable for dynamic data manipulation due to their mutable nature and ability to hold heterogeneous item types .
Before using 'os.remove' to delete files in Python, it is important to verify the file's existence with 'os.path.exists()' to prevent errors. Attempting to delete a non-existent file without this check will raise a FileNotFoundError, interrupting program flow. By confirming a file's existence, the code handles deletion operations smoothly and minimizes the risk of unhandled exceptions, resulting in more robust file management .
To handle HTTP errors gracefully in Python during API requests, the 'requests' library provides the 'raise_for_status()' method that raises an HTTPError for response status codes indicating an error (4xx, 5xx). This can be used in a try-except block, where exceptions such as requests.exceptions.HTTPError can be caught and handled appropriately. This approach prevents the application from crashing and allows for more informative and user-friendly error messages .
List comprehensions in Python provide a compact syntax for data transformation, enabling significant readability and performance improvements. They allow the application of an expression to each element of an iterable, producing a new list. For example, '[x**2 for x in range(10)]' generates a list of squares from 0 to 9. This single-line implementation reduces the need for additional looping constructs, making the code more expressive and often faster than equivalent for-loop implementations .
Implementing sessions in the Python 'requests' library is vital for maintaining state across multiple HTTP requests. Sessions allow the reuse of parameters such as headers, resulting in improved performance by minimizing the setup cost associated with each request. They also handle cookies automatically, keeping the session state intact. This is implemented using a 'requests.Session()' object to manage requests within a with statement, allowing headers to be set up once and overwhelmingly applied across multiple requests .
Exception handling in Python can manage network timeouts effectively using try-except blocks. In the context of network requests with the 'requests' library, timeouts can be set and handled by wrapping the request in a try-except block that catches 'requests.exceptions.Timeout'. This ensures that any delay beyond the specified timeout period is caught, providing an opportunity to log the error or try a fallback mechanism, thus improving application resilience .
Headers in HTTP requests are crucial for providing necessary metadata about the request or response. In Python, headers can be used for authentication, content-type specification, and more. They are implemented by including a 'headers' dictionary in the request function, e.g., 'requests.get(url, headers=headers)'. For secure requests, headers often include an 'Authorization' token, which ensures that only authorized users can access sensitive information .