S-Tier Python Cheat Sheet
Advanced Functions and Libraries for Masterful Python Programming
Core Mastery
Deep dive into iteration, evaluation, and type conversion with Python's built-in functions
Data Excellence
Harness the full power of NumPy, Pandas, and advanced data manipulation techniques
1. Core Python & Standard Library Mastery
1.1 Advanced Built-in Functions
Iteration and Looping
enumerate()
Adds counters to iterables with optional start parameter
for i, val in enumerate(['a', 'b', 'c'], start=1):
print(f"{i}: {val}")
iter()
Creates iterators with advanced callable/sentinel pattern
iterator = iter(lambda: file.read(1), '\n')
Code Execution and Evaluation
eval()
Evaluates single expressions with optional globals/locals
result = eval('2 * 3', {'x': 5})
exec()
Executes arbitrary code including statements
exec('x = 5; print(x)', {})
Security Note: Always validate input and use restricted execution environments with
globals and
locals parameters.
Data Type Conversion and Inspection
Type Conversion
int(), str(), float()
list(), set(), dict()
chr(), ord()
Object Inspection
isinstance(obj, type)
getattr(), setattr()
hasattr(), dir()
Introspection
vars() returns __dict__
type() for dynamic types
unicodedata.normalize()
1.2 System and Environment Interaction
Environment Variables & Command-Line Arguments
Environment Variables
# Accessing environment variables
import os
home = os.environ.get('HOME', '/default/path')
api_key = os.getenv('API_KEY')
# Setting environment variables
os.environ['MY_VAR'] = 'my_value'
Use
python-dotenv or
Dynaconf for advanced configuration management
Command-Line Arguments
import sys
script_name = sys.argv[0]
arguments = sys.argv[1:]
# For complex parsing:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--input', required=True)
System-Specific Parameters
Version & Platform
import sys
print(sys.version)
print(sys.version_info)
print(sys.platform)
I/O Streams
sys.stdin
sys.stdout
sys.stderr
sys.exit(code)
Module Management
sys.path
sys.modules
sys.maxsize
1.3 Functional Programming
itertools: Advanced Iterator Tools
tee
Clone iterators for parallel processing
from itertools import tee
it1, it2 = tee(iterable, 2)
⚠️ Be mindful of memory usage with uneven advancement
islice
Memory-efficient slicing of iterables
from itertools import islice
first_10 = islice(data, 10)
batch = islice(iterator, 100)
pairwise
Iterate over consecutive pairs (Python 3.10+)
from itertools import pairwise
for a, b in pairwise([1,2,3,4]):
chain & accumulate
Combine iterables and calculate running totals
from itertools import chain, accumulate
combined = chain('ABC', 'DEF')
running_total = accumulate([1,2,3,4])
functools: Function Manipulation
singledispatch
Dynamic function dispatch based on type
from functools import singledispatch
@singledispatch
def process(data): ...
lru_cache
Memoization for performance optimization
@lru_cache(maxsize=128)
def fibonacci(n): ...
wraps
Preserve function metadata in decorators
from functools import wraps
@wraps(func)
def wrapper(*args, **kwargs): ...
1.4 Context Managers and Resource Handling
Custom Context Managers
Class-based Approach
class DatabaseConnection:
def __enter__(self):
return self.connect()
def __exit__(self, exc_type, ...):
self.close()
contextlib Approach
from contextlib import contextmanager
@contextmanager
def managed_resource():
yield resource
contextlib Utilities
closing() - Auto-close resources
suppress() - Suppress specific exceptions
redirect_stdout() - Redirect output streams
ExitStack() - Manage multiple context managers
2. Data Manipulation and Analysis
2.1 Foundational Libraries
NumPy: Numerical Operations
ndarray Operations
import numpy as np
arr = np.array([1, 2, 3])
result = arr * 2 # Vectorized
Broadcasting
# Different shapes compatible
a = np.array([[1], [2], [3]])
b = np.array([1, 2, 3])
result = a + b
Key Features
- • Multi-dimensional arrays
- • Vectorized operations
- • Broadcasting mechanism
- • Mathematical functions
Pandas: DataFrame Manipulation
Data Structures
import pandas as pd
series = pd.Series([1, 2, 3])
df = pd.DataFrame({'col': [1, 2, 3]})
Data Operations
# Selection and filtering
df['col'] > 2
df.groupby('category').sum()
df.merge(other_df, on='key')
Key Features
- • DataFrame and Series objects
- • SQL-like operations
- • Data cleaning tools
- • Time series functionality
2.2 Advanced Pandas Techniques
Pivot Tables and Data Aggregation
Pivot Table Creation
pd.pivot_table(
df,
values='sales',
index='region',
columns='product',
aggfunc='sum',
fill_value=0
)
Cross-tabulation
pd.crosstab(
df['age_group'],
df['gender']
)
Combining DataFrames
Merge (SQL-style joins)
df1.merge(df2, on='key', how='inner')
Join (index-based)
df1.join(df2, lsuffix='_left')
Concatenate
pd.concat([df1, df2], axis=0)
Data Transformation
apply() - Axis operations
df.apply(func, axis=1)
map() - Value mapping
df['col'].map(mapping_dict)
transform() - Group operations
df.groupby('g').transform('mean')
2.3 Automating Data Workflows
Scripting Repetitive Tasks
Common Automation Pattern
def etl_pipeline(input_file, output_file):
# Extract
df = pd.read_csv(input_file)
# Transform
df_clean = clean_data(df)
df_transformed = transform_data(df_clean)
# Load
df_transformed.to_csv(output_file)
return df_transformed
- • Use functions to encapsulate logic
- • Command-line arguments for flexibility
- • Error handling and logging
- • Workflow management tools (Airflow, Luigi)
Scheduling with APScheduler
from apscheduler.schedulers.blocking import BlockingScheduler
scheduler = BlockingScheduler()
@scheduler.scheduled_job('interval', hours=1)
def scheduled_task():
print("Running hourly task")
scheduler.start()
3. File I/O and Filesystem Operations
3.1 Advanced File Handling
File Paths and Directories
pathlib (Modern)
from pathlib import Path
p = Path('/home/user/docs')
p.exists()
p.is_file()
new_file = p / 'document.txt'
os.path (Traditional)
import os
os.path.join('home', 'user')
os.path.split(path)
os.path.dirname(path)
File Metadata
import os
from datetime import datetime
stats = os.stat('file.txt')
size = stats.st_size
mtime = datetime.fromtimestamp(stats.st_mtime)
ctime = stats.st_ctime
High-Level File Operations (shutil)
Basic Operations
shutil.copy(src, dst) - Copy files
shutil.move(src, dst) - Move files
shutil.rmtree(path) - Remove directory tree
Archive Operations
shutil.make_archive() - Create archive
shutil.unpack_archive() - Extract archive
shutil.get_archive_formats() - Supported formats
3.2 Working with Different File Types
Text and Binary Files
Text Files
with open('file.txt', 'r') as f:
content = f.read()
Binary Files
with open('file.bin', 'rb') as f:
data = f.read()
CSV and Structured Data
csv module
import csv
with open('data.csv') as f:
reader = csv.DictReader(f)
for row in reader:
Pandas approach
import pandas as pd
df = pd.read_csv('data.csv')
df.to_csv('output.csv')
Serialization with pickle
Basic Usage
import pickle
with open('data.pkl', 'wb') as f:
pickle.dump(obj, f)
with open('data.pkl', 'rb') as f:
obj = pickle.load(f)
4. Networking and Inter-Process Communication
4.1 Socket Programming
TCP/IP Client-Server Architecture
Server Implementation
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('localhost', 12345))
server.listen(5)
client, addr = server.accept()
data = client.recv(1024)
client.send(b'Response')
Client Implementation
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('localhost', 12345))
client.send(b'Hello')
response = client.recv(1024)
Advanced Socket Patterns
Multi-threading
Handle multiple clients with threading module
Non-blocking I/O
Use select() for asynchronous operations
UDP Sockets
SOCK_DGRAM for connectionless communication
4.2 Network Automation and Configuration
Netmiko for Device Configuration
from netmiko import ConnectHandler
device = {
'device_type': 'cisco_ios',
'host': '192.168.1.1',
'username': 'admin',
'password': 'password'
}
with ConnectHandler(**device) as conn:
output = conn.send_command('show ip int brief')
Flexible Function Design
def configure_device(
host,
username='admin',
password=None,
commands=None,
**kwargs
):
# Implementation
- • Use keyword arguments for flexibility
- • Provide sensible default values
- • Accept **kwargs for extensibility
5. Graphical User Interfaces (GUIs)
5.1 Choosing a GUI Library
Tkinter for Simplicity
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text="Hello")
label.pack()
root.mainloop()
- • Included with Python
- • Simple and easy to learn
- • Good for small utilities
- • Basic widget set
PyQt for Professional Apps
from PyQt5.QtWidgets import *
app = QApplication([])
window = QWidget()
layout = QVBoxLayout()
layout.addWidget(QLabel("Hello"))
window.setLayout(layout)
window.show()
app.exec_()
- • Professional appearance
- • Rich widget collection
- • Excellent documentation
- • Commercial and GPL licenses
Kivy for Mobile/Touch
from kivy.app import App
from kivy.uix.label import Label
class MyApp(App):
def build(self):
return Label(text="Hello")
MyApp().run()
- • Touch interface support
- • Cross-platform (mobile/desktop)
- • Modern UI design
- • Gesture recognition
5.2 Advanced GUI Concepts
Custom Styling and Theming
Tkinter ttk
from tkinter import ttk
style = ttk.Style()
style.configure('TButton', ...)
PyQt Style Sheets
app.setStyleSheet("""
QPushButton { background-color: blue; }
""")
Kivy Kv Language
Button:
background_color: 1,0,0,1
Advanced Interactions
Drag-and-Drop
Implement drag sources and drop targets for intuitive data manipulation.
Multi-Touch Support
Handle gestures and multi-touch events for modern interfaces.
Custom Events
Create and handle custom events for application-specific interactions.
6. Data Visualization
6.1 Advanced Plotting with Matplotlib
Customizing Plots
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(x, y, color='red', linewidth=2)
ax.set_title('Custom Plot', fontsize=14)
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
ax.grid(True)
ax.legend(['Data Series'])
Subplots and Grid Layouts
# Multiple subplots
fig, axes = plt.subplots(2, 2)
axes[0, 0].plot(x1, y1)
axes[0, 1].scatter(x2, y2)
axes[1, 0].hist(data)
axes[1, 1].boxplot(data)
plt.tight_layout()
3D Plotting and Annotations
3D Plots
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z)
ax.scatter3D(x, y, z)
Annotations
ax.annotate('Important point',
xy=(x, y),
xytext=(x+1, y+1),
arrowprops=dict(arrowstyle='->'))
6.2 Statistical Visualization with Seaborn
Pair Plots and Heatmaps
import seaborn as sns
import matplotlib.pyplot as plt
# Pair plot
sns.pairplot(data, hue='category')
# Heatmap
sns.heatmap(correlation_matrix,
annot=True, cmap='coolwarm')
- • Automatic statistical visualization
- • Built-in themes and color palettes
- • Integration with Pandas DataFrames
Facet Grids and Violin Plots
# Facet Grid
g = sns.FacetGrid(data, col='category')
g.map(sns.histplot, 'value')
# Violin Plot
sns.violinplot(x='category',
y='value', data=data)
- • Conditional plotting with FacetGrid
- • Distribution visualization
- • Categorical data analysis
Saving and Displaying Plots
Exporting to Files
# Multiple formats
plt.savefig('plot.png', dpi=300)
plt.savefig('plot.pdf')
plt.savefig('plot.svg')
# Quality settings
plt.savefig('plot.jpg',
quality=95, bbox_inches='tight')
Interactive Environments
# Jupyter Notebook
%matplotlib inline
# or
%matplotlib notebook
# Interactive mode
plt.ion()
plt.show()
plt.ioff()