🐍 Python Snippet Library
Welcome to the most comprehensive Python snippet library on the web. This curated collection contains 100+ ready-to-use Python code examples covering everything from basic variables to advanced algorithms. Each snippet includes a detailed line-by-line explanation, making it perfect for both beginners learning Python and experienced developers looking for quick reference.
What You'll Find Here
Variables & Data Types – Learn how Python handles dynamic typing, strings, numbers, and more
Control Flow – Master if/elif/else, for loops, while loops, and pattern matching
Data Structures – Lists, dictionaries, sets, tuples with comprehensions and advanced operations
Functions & Lambdas – From basic functions to decorators, *args, **kwargs, and lambda expressions
Object-Oriented Programming – Classes, inheritance, properties, dataclasses, and the four pillars of OOP
Advanced Python – Generators, context managers, async/await, and type hints
Algorithms & Patterns – Binary search, quicksort, recursion, and design patterns like Singleton
File I/O & Data – Reading/writing files, JSON, CSV, and pathlib operations
Standard Library Modules – datetime, random, collections, itertools, re, and more
🚀 Why Every Programmer Should Learn Python
Python has become the most influential programming language of the 21st century . From powering AI algorithms and machine learning models to automating office tasks and building web backends, Python is everywhere. Its philosophy of "readable code is better than clever code" makes it accessible to beginners while remaining powerful enough for experts. Learning Python opens doors to careers in data science, backend engineering, DevOps, AI research, and more. The skills you gain here transfer directly to real-world applications, making you a more versatile and valuable developer.
This library is designed to accelerate your Python learning journey. Every snippet is interactive – you can copy, run, and modify code directly in your browser. Bookmark this page and return whenever you need a quick reference or want to learn a new Python concept.
Click Run to execute code in your browser using Pyodide. Click Explain for line-by-line breakdowns.
🔤 Variables & Data Types
Variable Assignment & Dynamic Typing
Python variables are dynamically typed — no type declaration needed. This example demonstrates assignment, multiple assignment, and swapping values.
name = "Glenn"
age = 28
height = 1.75
is_student = True
print (f"Name: {name}, Age: {age}, Height: {height}" )
x , y , z = 10 , 20 , 30
a , b = 5 , 10
a , b = b , a
Copy
Run
Explain
Line-by-line explanation
Line Explanation
name = "Glenn"Creates a string variable with value "Glenn"
age = 28Creates an integer variable with value 28
height = 1.75Creates a float variable with value 1.75
is_student = TrueCreates a boolean variable with value True (capitalized in Python)
print(f"Name: {name}...")f-string interpolation prints: Name: Glenn, Age: 28, Height: 1.75
x, y, z = 10, 20, 30Tuple unpacking: assigns three variables at once
a, b = 5, 10Assigns a=5, b=10
a, b = b, aSwaps values without a temporary variable: now a=10, b=5
variables dynamic typing assignment
String Operations
Common string methods including stripping whitespace, changing case, replacing substrings, joining, splitting, and slicing.
text = " Python Programming "
print (text.strip ())
print (text.upper ())
print (text.lower ())
print (text.replace ("Python" , "Java" ))
words = ["Python" , "is" , "awesome" ]
sentence = " " .join (words)
parts = sentence.split ()
name = "Glenn"
age = 28
print (f"My name is {name} and I am {age} years old" )
s = "Hello World"
print (s[0 :5 ])
print (s[6 :])
print (s[::-1 ])
Copy
Run
Explain
Line-by-line explanation
Line Explanation
text = " Python Programming "Creates a string with leading/trailing spaces
text.strip()Removes whitespace → "Python Programming"
text.upper()Converts to uppercase → " PYTHON PROGRAMMING "
text.lower()Converts to lowercase → " python programming "
text.replace("Python","Java")Replaces substring → " Java Programming "
" ".join(words)Joins list elements with space → "Python is awesome"
sentence.split()Splits by whitespace → ["Python","is","awesome"]
f"My name is {name}..."f-string interpolation with variables
s[0:5]Slicing: characters 0-4 → "Hello"
s[6:]Slicing: from index 6 to end → "World"
s[::-1]Reverse string using step -1 → "dlroW olleH"
strings f-strings slicing join
Numeric Operations
Working with integers, floats, arithmetic operators, floor division, modulo, exponentiation, and the math module.
import math
a , b = 10 , 3
print (a + b )
print (a - b )
print (a * b )
print (a / b )
print (a // b )
print (a % b )
print (a ** b )
print (math.sqrt (16 ))
print (math.ceil (3.14 ))
print (math.floor (3.14 ))
print (math.pow (2 , 8 ))
print (math.pi )
print (math.e )
Copy
Run
Explain
Line-by-line explanation
Line Explanation
import mathImports the math module for mathematical functions
a, b = 10, 3Assigns a=10, b=3
a + bAddition → 13
a - bSubtraction → 7
a * bMultiplication → 30
a / bDivision (float) → 3.333...
a // bFloor division (integer) → 3
a % bModulo (remainder) → 1
a ** bExponentiation → 1000 (10³)
math.sqrt(16)Square root → 4.0
math.ceil(3.14)Ceiling (rounds up) → 4
math.floor(3.14)Floor (rounds down) → 3
math.pow(2, 8)Power function → 256.0 (2⁸)
math.piPi constant (π ≈ 3.14159...)
math.eEuler's number (e ≈ 2.71828...)
numbers math operators
🔄 Control Flow
If-Elif-Else Conditions
Conditional statements with indentation, including the ternary operator for concise conditionals.
score = 85
if score >= 90 :
grade = "A"
elif score >= 80 :
grade = "B"
elif score >= 70 :
grade = "C"
else :
grade = "F"
print (f"Grade: {grade}" )
age = 18
status = "Adult" if age >= 18 else "Minor"
print (status )
Copy
Run
Explain
Line-by-line explanation
Line Explanation
score = 85Sets the score value
if score >= 90:Checks if score is 90 or higher → False (85≥90 is false)
elif score >= 80:Checks if score is 80 or higher → True (85≥80), so grade = "B"
elif score >= 70:Skipped because previous condition was true
else:Skipped because previous condition was true
print(f"Grade: {grade}")Outputs "Grade: B"
age = 18Sets age value
status = "Adult" if age >= 18 else "Minor"Ternary operator: if age≥18, returns "Adult", else "Minor"
print(status)Outputs "Adult"
if/elif/else ternary
For Loops
Iterating over iterables including lists, using enumerate for index-value pairs, and the range function.
fruits = ["apple" , "banana" , "cherry" ]
for fruit in fruits :
print (fruit )
for i , fruit in enumerate (fruits , 1 ):
print (f"{i}. {fruit}" )
for i in range (5 ):
print (i , end =" " )
for i in range (2 , 10 , 2 ):
print (i , end =" " )
Copy
Run
Explain
Line-by-line explanation
Line Explanation
fruits = ["apple", "banana", "cherry"]Creates a list of fruit names
for fruit in fruits:Iterates through each element in the list
print(fruit)Prints each fruit on a new line
enumerate(fruits, 1)Returns (index, value) pairs starting from 1
print(f"{i}. {fruit}")Prints numbered list: "1. apple", "2. banana", etc.
range(5)Generates numbers 0, 1, 2, 3, 4
range(2, 10, 2)Generates even numbers: 2, 4, 6, 8
end=" "Prints on same line with space separator
for loops range enumerate
While Loops
Loops that run while a condition is true, including infinite loops with break statements.
count = 0
while count < 5 :
print (count , end =" " )
count += 1
num = 10
while num > 0 :
print (num , end =" " )
num -= 1
while True :
user_input = input ("Enter 'quit' to exit: " )
if user_input == "quit" :
break
Copy
Run
Explain
Line-by-line explanation
Line Explanation
count = 0Initializes counter
while count < 5:Loop continues while count is less than 5
print(count, end=" ")Prints count on same line with space
count += 1Increments count by 1
num = 10Sets starting value for countdown
while num > 0:Loop continues while num is positive
num -= 1Decrements num by 1
while True:Infinite loop
if user_input == "quit":Checks for exit condition
breakExits the loop immediately
while loops break
Match Statement (Python 3.10+)
Structural pattern matching for elegant conditional logic, including pattern guards and tuple patterns.
value = 42
match value :
case 0 :
print ("Zero" )
case 42 :
print ("The answer" )
case n if n > 0 :
print ("Positive" )
case _ :
print ("Other" )
point = (3 , 4 )
match point :
case (0 , 0 ):
print ("Origin" )
case (x , 0 ):
print (f"On X-axis at {x}" )
case (0 , y ):
print (f"On Y-axis at {y}" )
case (x , y ):
print (f"Point at ({x}, {y})" )
Copy
Run
Explain
Line-by-line explanation
Line Explanation
value = 42Sets the value to match
match value:Begins pattern matching on value
case 42:Matches if value is exactly 42 → prints "The answer"
case n if n > 0:Pattern guard: matches any positive number (n > 0)
case _:Wildcard: matches anything (fallback)
point = (3, 4)Creates a tuple representing a point
match point:Begins pattern matching on the tuple
case (0, 0):Matches origin point
case (x, 0):Matches any point on X-axis (y=0), captures x
case (0, y):Matches any point on Y-axis (x=0), captures y
case (x, y):Matches any point, captures both coordinates
match pattern matching
📋 Data Structures
List Operations
Comprehensive list operations including append, insert, pop, remove, list comprehensions, and matrix indexing.
numbers = [1 , 2 , 3 , 4 , 5 ]
numbers .append (6 )
numbers .insert (0 , 0 )
popped = numbers .pop ()
numbers .remove (3 )
squares = [x **2 for x in range (10 )]
evens = [x for x in range (10 ) if x % 2 == 0 ]
matrix = [[1 , 2 , 3 ], [4 , 5 , 6 ], [7 , 8 , 9 ]]
print (matrix [1 ][1 ])
nums = [3 , 1 , 4 , 1 , 5 , 9 , 2 ]
nums .sort ()
nums .sort (reverse =True )
Copy
Run
Explain
Line-by-line explanation
Line Explanation
numbers = [1, 2, 3, 4, 5]Creates a list of numbers
numbers.append(6)Adds 6 to the end of the list → [1,2,3,4,5,6]
numbers.insert(0, 0)Inserts 0 at index 0 → [0,1,2,3,4,5,6]
popped = numbers.pop()Removes and returns the last element (6)
numbers.remove(3)Removes the first occurrence of 3
[x**2 for x in range(10)]List comprehension: squares of 0-9
[x for x in range(10) if x%2==0]List comprehension with filter: even numbers 0-9
matrix[1][1]Accesses element at row 1, column 1 → 5
nums.sort()Sorts list in ascending order
nums.sort(reverse=True)Sorts list in descending order
lists comprehensions sort
Dictionary Operations
Key-value stores with O(1) lookup, safe access with get(), iteration, comprehensions, and defaultdict.
person = {"name" : "Glenn" , "age" : 28 , "city" : "Manila" }
print (person ["name" ])
print (person .get ("country" , "Unknown" ))
person ["country" ] = "Philippines"
for key , value in person .items ():
print (f"{key}: {value}" )
squares = {x : x **2 for x in range (5 )}
from collections import defaultdict
counts = defaultdict (int )
counts ["apple" ] += 1
Copy
Run
Explain
Line-by-line explanation
Line Explanation
person = {"name":"Glenn", ...}Creates a dictionary with key-value pairs
person["name"]Accesses value by key → "Glenn"
person.get("country", "Unknown")Safely accesses key with default → "Unknown"
person["country"] = "Philippines"Adds a new key-value pair
for key, value in person.items():Iterates over all key-value pairs
{x: x**2 for x in range(5)}Dictionary comprehension: {0:0, 1:1, 2:4, 3:9, 4:16}
defaultdict(int)Creates a dict that auto-creates missing keys with default value 0
counts["apple"] += 1Increments count for "apple" (auto-creates if missing)
dictionaries defaultdict comprehensions
Set Operations
Unordered collections of unique elements with set operations: union, intersection, difference, and symmetric difference.
a = {1 , 2 , 3 , 4 }
b = {3 , 4 , 5 , 6 }
print (a | b )
print (a & b )
print (a - b )
print (a ^ b )
a .add (7 )
a .discard (1 )
unique = set ([1 , 2 , 2 , 3 , 3 , 3 ])
squares = {x **2 for x in range (5 )}
Copy
Run
Explain
Line-by-line explanation
Line Explanation
a = {1, 2, 3, 4}Creates set a with elements 1,2,3,4
b = {3, 4, 5, 6}Creates set b with elements 3,4,5,6
a | bUnion: combines both sets → {1,2,3,4,5,6}
a & bIntersection: common elements → {3,4}
a - bDifference: elements in a but not b → {1,2}
a ^ bSymmetric difference: elements in either but not both → {1,2,5,6}
a.add(7)Adds element 7 to set a
a.discard(1)Removes element 1 if present (no error if missing)
set([1,2,2,3,3,3])Creates a set from list, removing duplicates → {1,2,3}
{x**2 for x in range(5)}Set comprehension: squares of 0-4 → {0,1,4,9,16}
sets union intersection
Tuples & Unpacking
Immutable sequences with packing, unpacking, extended unpacking, and namedtuple.
coords = (3 , 4 )
x , y = coords
first , *rest = [1 , 2 , 3 , 4 , 5 ]
from collections import namedtuple
Point = namedtuple ("Point" , ["x" , "y" ])
p = Point (3 , 4 )
print (p .x , p .y )
data = 1 , 2 , 3
a , b , c = data
Copy
Run
Explain
Line-by-line explanation
Line Explanation
coords = (3, 4)Creates a tuple with two elements
x, y = coordsTuple unpacking: x=3, y=4
first, *rest = [1,2,3,4,5]Extended unpacking: first=1, rest=[2,3,4,5]
namedtuple("Point", ["x","y"])Creates a namedtuple class with fields x and y
p = Point(3, 4)Creates a namedtuple instance
p.x, p.yAccesses fields by name (also supports index access)
data = 1, 2, 3Implicit tuple creation (parentheses optional)
a, b, c = dataUnpacks tuple into three variables
tuples unpacking namedtuple
🛠️ Functions & Lambdas
Function Definition & Arguments
Defining functions with default arguments, variable positional arguments (*args), and keyword arguments (**kwargs).
def greet (name , greeting ="Hello" ):
return f"{greeting}, {name}!"
def sum_all (*args ):
return sum (args )
def print_kwargs (**kwargs ):
for key , value in kwargs .items ():
print (f"{key}: {value}" )
def describe (name , age , city ="Unknown" ):
return f"{name} is {age} years old from {city}"
print (greet ("Glenn" ))
print (sum_all (1 , 2 , 3 , 4 , 5 ))
print_kwargs (name ="Alice" , age =30 )
Copy
Run
Explain
Line-by-line explanation
Line Explanation
def greet(name, greeting="Hello"):Defines a function with a default parameter
return f"{greeting}, {name}!"Returns a formatted greeting string
def sum_all(*args):Accepts any number of positional arguments as a tuple
return sum(args)Calculates sum of all arguments
def print_kwargs(**kwargs):Accepts any number of keyword arguments as a dict
for key, value in kwargs.items():Iterates through keyword arguments
print(greet("Glenn"))Calls function with only required argument → "Hello, Glenn!"
sum_all(1,2,3,4,5)Passes multiple arguments to *args → returns 15
print_kwargs(name="Alice", age=30)Passes keyword arguments → prints "name: Alice", "age: 30"
functions *args **kwargs
Lambda Functions
Anonymous functions used with map, filter, and sorted for concise functional programming.
square = lambda x : x ** 2
add = lambda a , b : a + b
numbers = [1 , 2 , 3 , 4 , 5 ]
squared = list (map (lambda x : x ** 2 , numbers ))
evens = list (filter (lambda x : x % 2 == 0 , numbers ))
people = [{"name" : "Alice" , "age" : 30 }, {"name" : "Bob" , "age" : 25 }]
sorted_people = sorted (people , key =lambda p : p ["age" ])
Copy
Run
Explain
Line-by-line explanation
Line Explanation
square = lambda x: x ** 2Lambda that squares its argument
add = lambda a, b: a + bLambda with two arguments
map(lambda x: x**2, numbers)Applies lambda to each element → [1,4,9,16,25]
filter(lambda x: x%2==0, numbers)Keeps only even numbers → [2,4]
sorted(people, key=lambda p: p['age'])Sorts list of dicts by the 'age' key → Bob (25) then Alice (30)
lambda map filter
Decorators
Functions that modify other functions, with timing example and proper metadata preservation using functools.wraps.
import time
from functools import wraps
def timer (func ):
@wraps (func )
def wrapper (*args , **kwargs ):
start = time.time ()
result = func (*args , **kwargs )
end = time.time ()
print (f"{func.__name__} took {end - start:.4f} seconds" )
return result
return wrapper
@timer
def slow_function ():
time.sleep (1 )
return "Done"
Copy
Run
Explain
Line-by-line explanation
Line Explanation
import timeImports time module for measuring execution
from functools import wrapsImports wraps to preserve function metadata
def timer(func):Decorator factory that takes a function
@wraps(func)Preserves the original function's name, docstring, etc.
def wrapper(*args, **kwargs):Wrapper function that adds timing
start = time.time()Records start time
result = func(*args, **kwargs)Calls the original function
end = time.time()Records end time
print(f"{func.__name__} took...")Prints execution time
@timerApplies the timer decorator to slow_function
time.sleep(1)Simulates a slow operation (1 second)
decorators timing
🏗️ Object-Oriented Programming
Class Definition & Methods
Creating classes with attributes, methods, __init__ constructor, and __str__ representation.
class Car :
def __init__ (self , make , model , year ):
self .make = make
self .model = model
self .year = year
self .odometer = 0
def drive (self , miles ):
self .odometer += miles
return f"Driven {miles} miles. Total: {self.odometer}"
def __str__ (self ):
return f"{self.year} {self.make} {self.model}"
car = Car ("Toyota" , "Camry" , 2023 )
print (car )
print (car .drive (50 ))
Copy
Run
Explain
Line-by-line explanation
Line Explanation
class Car:Defines a new class named Car
def __init__(self, make, model, year):Constructor called when creating a new instance
self.make = makeAssigns instance attribute make
self.odometer = 0Sets default attribute value
def drive(self, miles):Instance method that updates odometer
self.odometer += milesAdds miles to the odometer
def __str__(self):String representation method (called by print())
return f"{self.year} {self.make} {self.model}"Returns readable string representation
car = Car("Toyota", "Camry", 2023)Creates an instance of Car
print(car)Calls __str__ method → "2023 Toyota Camry"
car.drive(50)Calls drive method → "Driven 50 miles. Total: 50"
class __init__ __str__
Inheritance & super()
Extending classes with inheritance and using super() to call parent methods.
class Animal :
def __init__ (self , name ):
self .name = name
def speak (self ):
raise NotImplementedError
class Dog (Animal ):
def speak (self ):
return f"{self.name} says Woof!"
class GoldenRetriever (Dog ):
def speak (self ):
return f"{super().speak()} And I'm a Golden Retriever!"
dog = Dog ("Rex" )
golden = GoldenRetriever ("Buddy" )
print (dog .speak ())
print (golden .speak ())
Copy
Run
Explain
Line-by-line explanation
Line Explanation
class Animal:Base class (parent)
def speak(self):Abstract method that must be overridden
raise NotImplementedErrorForces subclasses to implement speak()
class Dog(Animal):Dog inherits from Animal
def speak(self):Overrides speak method
return f"{self.name} says Woof!"Returns dog's sound
class GoldenRetriever(Dog):GoldenRetriever inherits from Dog
super().speak()Calls parent's speak method
dog = Dog("Rex")Creates Dog instance
golden = GoldenRetriever("Buddy")Creates GoldenRetriever instance
dog.speak()Calls Dog's speak → "Rex says Woof!"
golden.speak()Calls GoldenRetriever's speak → "Buddy says Woof! And I'm a Golden Retriever!"
inheritance super polymorphism
Property Decorators
Getters and setters with validation using @property and @setter decorators.
class BankAccount :
def __init__ (self , owner , balance =0 ):
self .owner = owner
self ._balance = balance
@property
def balance (self ):
return self ._balance
@balance .setter
def balance (self , value ):
if value < 0 :
raise ValueError ("Balance cannot be negative" )
self ._balance = value
def deposit (self , amount ):
if amount <= 0 :
raise ValueError ("Amount must be positive" )
self ._balance += amount
acc = BankAccount ("Glenn" , 1000 )
print (acc .balance )
acc .deposit (500 )
print (acc .balance )
Copy
Run
Explain
Line-by-line explanation
Line Explanation
@propertyMakes balance method a getter (accessed like attribute)
@balance.setterMakes balance method a setter with validation
if value < 0: raise ValueErrorPrevents negative balance assignment
self._balance = valueSets the internal balance value
def deposit(self, amount):Method that adds money
if amount <= 0: raise ValueErrorValidates deposit amount
acc.balanceProperty access (calls getter) → 1000
acc.deposit(500)Adds 500 to balance → 1500
@property getter setter
Dataclasses
Reducing boilerplate with dataclasses, including default values and mutable defaults with default_factory.
from dataclasses import dataclass, field
from typing import List
@dataclass
class Person :
name : str
age : int
email : str = ""
hobbies : List [str ] = field (default_factory =list )
@property
def is_adult (self ) -> bool :
return self .age >= 18
person = Person ("Alice" , 30 , "alice@example.com" )
person .hobbies .extend (["reading" , "coding" ])
print (person )
print (person .is_adult )
Copy
Run
Explain
Line-by-line explanation
Line Explanation
@dataclassAuto-generates __init__, __repr__, __eq__, and other methods
name: strField with type annotation (required)
email: str = ""Field with default value
hobbies: List[str] = field(default_factory=list)Mutable default: uses factory to create new list per instance
@propertyComputed property that returns boolean based on age
person = Person("Alice", 30, ...)Creates instance with provided values
person.hobbies.extend([...])Adds hobbies to the list
print(person)Calls auto-generated __repr__ → "Person(name='Alice', age=30, email='alice@example.com', hobbies=['reading', 'coding'])"
print(person.is_adult)Property access → True (age 30 >= 18)
dataclass boilerplate
⚡ Advanced Python
Generators & Yield
Lazy iteration using generator functions that yield values one at a time, saving memory.
def fibonacci_generator (n ):
a , b = 0 , 1
for _ in range (n ):
yield a
a , b = b , a + b
gen = fibonacci_generator (10 )
for num in gen :
print (num , end =" " )
Copy
Run
Explain
Line-by-line explanation
Line Explanation
def fibonacci_generator(n):Defines a generator function
a, b = 0, 1Initializes Fibonacci sequence
for _ in range(n):Loops n times
yield aPauses and returns current value (lazy evaluation)
a, b = b, a + bUpdates to next Fibonacci numbers
gen = fibonacci_generator(10)Creates generator object (no computation yet)
for num in gen:Iterates through generator (computes on demand)
print(num, end=" ")Prints: 0 1 1 2 3 5 8 13 21 34
generators yield
Context Managers
Resource management with the with statement, implementing __enter__ and __exit__.
class ManagedFile :
def __init__ (self , filename , mode ):
self .filename = filename
self .mode = mode
def __enter__ (self ):
self .file = open (self .filename , self .mode )
return self .file
def __exit__ (self , exc_type , exc_val , exc_tb ):
if self .file :
self .file .close ()
with ManagedFile ("example.txt" , "w" ) as f :
f .write ("Hello, World!" )
Copy
Run
Explain
Line-by-line explanation
Line Explanation
class ManagedFile:Defines a context manager class
def __enter__(self):Called when entering with statement
self.file = open(...)Opens the file
return self.fileReturns the file object to be used in the with block
def __exit__(...):Called when exiting the with block (even if exception occurs)
if self.file: self.file.close()Closes the file if it was opened
with ManagedFile(...) as f:Uses the context manager
f.write("Hello, World!")Writes to the file
context manager with
Async/Await
Asynchronous programming with asyncio for concurrent I/O operations.
import asyncio
async def fetch_data (name , delay ):
await asyncio.sleep (delay )
return f"Data from {name}"
async def main ():
results = await asyncio.gather (
fetch_data ("API 1" , 1 ),
fetch_data ("API 2" , 0.5 ),
fetch_data ("API 3" , 1.5 )
)
for result in results :
print (result )
asyncio .run (main ())
Copy
Run
Explain
Line-by-line explanation
Line Explanation
import asyncioImports the asyncio library for async programming
async def fetch_data(...):Defines an asynchronous coroutine
await asyncio.sleep(delay)Pauses coroutine without blocking the event loop
async def main():Main async function
await asyncio.gather(...)Runs multiple coroutines concurrently
asyncio.run(main())Starts the event loop and runs the main coroutine
async await asyncio
Type Hints
Adding type information for better code documentation and static analysis with mypy.
from typing import List, Dict, Optional
def greet (name : str ) -> str :
return f"Hello, {name}"
def process_numbers (numbers : List [int ]) -> List [int ]:
return [n * 2 for n in numbers ]
def find_user (user_id : int ) -> Optional [Dict [str , str ]]:
if user_id == 1 :
return {"name" : "Glenn" }
return None
Copy
Run
Explain
Line-by-line explanation
Line Explanation
from typing import List, Dict, OptionalImports type hinting utilities
def greet(name: str) -> str:Function takes string, returns string
def process_numbers(numbers: List[int]) -> List[int]:Function takes list of ints, returns list of ints
-> Optional[Dict[str, str]]Function may return a dict or None
if user_id == 1: return {"name": "Glenn"}Returns a dict if user exists
return NoneReturns None if user not found
type hints typing
🧮 Algorithms & Patterns
Binary Search
Efficient O(log n) search algorithm for sorted arrays.
def binary_search (arr , target ):
left , right = 0 , len (arr ) - 1
while left <= right :
mid = (left + right ) // 2
if arr [mid ] == target :
return mid
elif arr [mid ] < target :
left = mid + 1
else :
right = mid - 1
return -1
arr = [1 , 3 , 5 , 7 , 9 , 11 , 13 ]
print (binary_search (arr , 7 ))
print (binary_search (arr , 4 ))
Copy
Run
Explain
Line-by-line explanation
Line Explanation
left, right = 0, len(arr) - 1Sets search boundaries
while left <= right:Continues while search space is valid
mid = (left + right) // 2Calculates middle index (floor division)
if arr[mid] == target:Found the target → returns index
elif arr[mid] < target:Target is in right half → moves left boundary
else:Target is in left half → moves right boundary
return -1Target not found in array
arr = [1,3,5,7,9,11,13]Sorted array for searching
binary_search(arr, 7)Searches for 7 → returns 3 (index position)
binary_search(arr, 4)Searches for 4 → returns -1 (not found)
binary search algorithm
Quicksort
Divide and conquer sorting algorithm with O(n log n) average time complexity.
def quicksort (arr ):
if len (arr ) <= 1 :
return arr
pivot = arr [len (arr ) // 2 ]
left = [x for x in arr if x < pivot ]
middle = [x for x in arr if x == pivot ]
right = [x for x in arr if x > pivot ]
return quicksort (left ) + middle + quicksort (right )
data = [3 , 6 , 8 , 10 , 1 , 2 , 1 ]
print (quicksort (data ))
Copy
Run
Explain
Line-by-line explanation
Line Explanation
if len(arr) <= 1: return arrBase case: arrays with 0 or 1 elements are already sorted
pivot = arr[len(arr) // 2]Selects the middle element as pivot
left = [x for x in arr if x < pivot]List comprehension: elements less than pivot
middle = [x for x in arr if x == pivot]Elements equal to pivot
right = [x for x in arr if x > pivot]Elements greater than pivot
return quicksort(left) + middle + quicksort(right)Recursively sorts left and right, then combines
data = [3,6,8,10,1,2,1]Unsorted array
print(quicksort(data))Outputs sorted array: [1,1,2,3,6,8,10]
quicksort sorting
Recursive Factorial
Classic recursion example: calculating factorial with base case and recursive step.
def factorial (n ):
if n <= 1 :
return 1
return n * factorial (n - 1 )
print (factorial (5 ))
Copy
Run
Explain
Line-by-line explanation
Line Explanation
def factorial(n):Defines recursive factorial function
if n <= 1: return 1Base case: 0! = 1 and 1! = 1
return n * factorial(n - 1)Recursive step: n! = n * (n-1)!
print(factorial(5))Calculates 5! = 5*4*3*2*1 = 120
recursion factorial
Singleton Pattern
Design pattern that ensures only one instance of a class exists.
class SingletonMeta (type ):
_instances = {}
def __call__ (cls , *args , **kwargs ):
if cls not in cls ._instances :
cls ._instances [cls ] = super ().__call__ (*args , **kwargs )
return cls ._instances [cls ]
class Config (metaclass =SingletonMeta ):
def __init__ (self ):
self .settings = {"debug" : True }
c1 = Config ()
c2 = Config ()
print (c1 is c2 )
Copy
Run
Explain
Line-by-line explanation
Line Explanation
class SingletonMeta(type):Metaclass for Singleton pattern
_instances = {}Dictionary to store instances
def __call__(cls, *args, **kwargs):Intercepts instance creation
if cls not in cls._instances:Checks if instance already exists
cls._instances[cls] = super().__call__(...)Creates instance only once
return cls._instances[cls]Returns the single instance
class Config(metaclass=SingletonMeta):Config class using Singleton metaclass
c1 = Config(); c2 = Config()Both calls return the same instance
print(c1 is c2)True (both variables point to same object)
singleton design pattern
📁 File I/O & Data
Reading & Writing Files
Using context managers to safely read, write, and append files with proper encoding.
with open ("data.txt" , "r" , encoding ="utf-8" ) as f :
content = f .read ()
with open ("output.txt" , "w" , encoding ="utf-8" ) as f :
f .write ("Hello, World!\n" )
f .writelines (["Line 1\n" , "Line 2\n" ])
with open ("log.txt" , "a" , encoding ="utf-8" ) as f :
f .write ("New entry\n" )
Copy
Run
Explain
Line-by-line explanation
Line Explanation
with open("data.txt", "r", encoding="utf-8") as f:Opens file in read mode with UTF-8 encoding
content = f.read()Reads entire file content into string
with open("output.txt", "w", encoding="utf-8") as f:Opens file in write mode (overwrites if exists)
f.write("Hello, World!\n")Writes a line to the file
f.writelines(["Line 1\n", "Line 2\n"])Writes multiple lines at once
with open("log.txt", "a", encoding="utf-8") as f:Opens file in append mode (adds to end)
f.write("New entry\n")Appends a line to the file
file I/O read write
JSON Handling
Encoding Python objects to JSON and decoding JSON back to Python objects.
import json
data = {"name" : "Glenn" , "age" : 28 , "hobbies" : ["coding" , "reading" ]}
json_str = json.dumps (data , indent =2 )
print (json_str )
parsed = json.loads (json_str )
print (parsed ["name" ])
with open ("data.json" , "w" ) as f :
json.dump (data , f , indent =2 )
Copy
Run
Explain
Line-by-line explanation
Line Explanation
import jsonImports JSON module
data = {"name": "Glenn", ...}Python dictionary
json.dumps(data, indent=2)Converts Python dict to JSON string with indentation
json.loads(json_str)Parses JSON string back to Python dict
parsed["name"]Accesses value from parsed data → "Glenn"
with open("data.json", "w") as f:Opens file for writing
json.dump(data, f, indent=2)Writes JSON to file with indentation
json dumps loads
CSV Parsing
Reading and writing CSV files using DictReader and DictWriter.
import csv
from io import StringIO
data = """name,age,city
Alice,30,New York
Bob,25,Los Angeles
Charlie,35,Chicago"""
reader = csv.DictReader (StringIO (data ))
for row in reader :
print (f"{row['name']} is {row['age']} in {row['city']}" )
Copy
Run
Explain
Line-by-line explanation
Line Explanation
import csvImports csv module
from io import StringIOImports StringIO for in-memory file operations
data = """..."""Multi-line string containing CSV data
csv.DictReader(StringIO(data))Creates CSV reader that treats each row as dict
for row in reader:Iterates through each row
print(f"{row['name']} is {row['age']} in {row['city']}")Accesses values by column name
csv DictReader
pathlib Path Operations
Modern path handling with pathlib for cross-platform file operations.
from pathlib import Path
path = Path ("example.txt" )
path .write_text ("Hello, World!" , encoding ="utf-8" )
content = path .read_text (encoding ="utf-8" )
print (path .name )
print (path .stem )
print (path .suffix )
Copy
Run
Explain
Line-by-line explanation
Line Explanation
from pathlib import PathImports Path class for object-oriented path handling
path = Path("example.txt")Creates a Path object
path.write_text("Hello, World!", encoding="utf-8")Writes text to file (creates if doesn't exist)
content = path.read_text(encoding="utf-8")Reads text from file
path.nameReturns filename with extension: "example.txt"
path.stemReturns filename without extension: "example"
path.suffixReturns file extension: ".txt"
pathlib Path
🧪 Testing & Error Handling
Exception Handling
Graceful error handling with try/except/else/finally blocks.
try :
result = 10 / 0
except ZeroDivisionError as e :
print (f"Error: {e}" )
try :
value = int ("abc" )
except ValueError :
print ("Invalid value" )
else :
print ("Success!" )
finally :
print ("Cleanup" )
Copy
Run
Explain
Line-by-line explanation
Line Explanation
try: result = 10 / 0Attempts division by zero (raises ZeroDivisionError)
except ZeroDivisionError as e:Catches the specific exception
print(f"Error: {e}")Prints error message
try: value = int("abc")Attempts to convert string to int (raises ValueError)
except ValueError:Catches ValueError
else:Runs only if no exception occurred in try block
finally:Always runs regardless of exception (for cleanup)
exceptions try/except
Pytest Basics
Writing simple tests with assert statements.
def add (a , b ):
return a + b
def test_add ():
assert add (2 , 3 ) == 5
assert add (-1 , 1 ) == 0
test_add ()
Copy
Run
Explain
Line-by-line explanation
Line Explanation
def add(a, b): return a + bSimple function to test
def test_add():Test function (pytest convention)
assert add(2, 3) == 5Assertion: verifies expected output
assert add(-1, 1) == 0Another assertion test
test_add()Runs the test (assertions pass silently if no errors)
testing pytest assert
🧰 Standard Library Modules
datetime
Working with dates and times: formatting, parsing, and arithmetic.
from datetime import datetime, timedelta
now = datetime.now ()
print (now.strftime ("%Y-%m-%d %H:%M" ))
tomorrow = now + timedelta (days =1 )
dt = datetime.strptime ("2026-06-18" , "%Y-%m-%d" )
print (dt .year )
Copy
Run
Explain
Line-by-line explanation
Line Explanation
from datetime import datetime, timedeltaImports datetime and timedelta classes
now = datetime.now()Gets current date and time
now.strftime("%Y-%m-%d %H:%M")Formats datetime as string
now + timedelta(days=1)Adds one day to current date
datetime.strptime("2026-06-18", "%Y-%m-%d")Parses string to datetime object
dt.yearAccesses year component → 2026
datetime strftime
random
Generating random numbers and making random selections.
import random
rand_int = random.randint (1 , 100 )
rand_float = random.random ()
choice = random.choice (["apple" , "banana" , "cherry" ])
print (rand_int , rand_float , choice )
Copy
Run
Explain
Line-by-line explanation
Line Explanation
import randomImports random module
random.randint(1, 100)Random integer between 1 and 100 (inclusive)
random.random()Random float between 0.0 and 1.0
random.choice(["apple", "banana", "cherry"])Randomly selects one element from list
random randint
collections – Counter & defaultdict
Specialized containers: Counter for counting, defaultdict for auto-creating missing keys.
from collections import Counter, defaultdict
words = ["apple" , "banana" , "apple" , "cherry" , "banana" , "apple" ]
counter = Counter (words )
print (counter .most_common (1 ))
graph = defaultdict (list )
graph ["A" ].append ("B" )
Copy
Run
Explain
Line-by-line explanation
Line Explanation
from collections import Counter, defaultdictImports Counter and defaultdict
words = ["apple", "banana", ...]List with duplicate entries
Counter(words)Counts occurrences of each element
counter.most_common(1)Returns the most frequent element: [("apple", 3)]
defaultdict(list)Creates a dict that auto-creates list for missing keys
graph["A"].append("B")Appends "B" to list at key "A" (auto-creates list)
collections Counter defaultdict
itertools
Efficient looping with combinatoric iterators.
import itertools
perms = list (itertools.permutations ([1 , 2 , 3 ], 2 ))
print (perms [:3 ])
Copy
Run
Explain
Line-by-line explanation
Line Explanation
import itertoolsImports itertools for efficient looping
itertools.permutations([1,2,3], 2)Generates all ordered permutations of length 2
list(...)Converts iterator to list
perms[:3]First 3 permutations: [(1,2), (1,3), (2,1)]
itertools permutations
re – Regular Expressions
Pattern matching and extraction using regular expressions.
import re
text = "Contact: glenn@example.com"
emails = re.findall (r"[\w.+-]+@[\w-]+\.\w+" , text )
print (emails )
Copy
Run
Explain
Line-by-line explanation
Line Explanation
import reImports regular expression module
text = "Contact: glenn@example.com"Sample text containing an email
re.findall(r"[\w.+-]+@[\w-]+\.\w+", text)Finds all email addresses using regex pattern
print(emails)Outputs: ["glenn@example.com"]
regex re
📦 Data Structures & Algorithms
Singly Linked List
Implementation with traversal and insertion using Node and LinkedList classes.
class Node :
def __init__ (self , data ):
self .data = data
self .next = None
class LinkedList :
def __init__ (self ):
self .head = None
def append (self , data ):
new_node = Node (data )
if not self .head :
self .head = new_node
return
current = self .head
while current .next :
current = current .next
current .next = new_node
def display (self ):
elements = []
current = self .head
while current :
elements .append (current .data )
current = current .next
return elements
ll = LinkedList ()
for i in range (1 , 6 ):
ll .append (i )
print (ll .display ())
Copy
Run
Explain
Line-by-line explanation
Line Explanation
class Node:Node class with data and pointer to next node
def __init__(self, data):Initializes node with data
self.next = NonePointer to next node (initially None)
class LinkedList:Linked list class with head pointer
def append(self, data):Adds node to end of list
if not self.head:If list is empty, set head to new node
while current.next:Traverses to last node
current.next = new_nodeLinks last node to new node
def display(self):Returns list of all data values
for i in range(1,6): ll.append(i)Builds list 1→5
print(ll.display())Outputs [1, 2, 3, 4, 5]
linked list data structure
Stack (LIFO) with List
Stack implementation using a list with push, pop, and peek operations.
class Stack :
def __init__ (self ):
self .items = []
def push (self , item ):
self .items .append (item )
def pop (self ):
if not self .is_empty ():
return self .items .pop ()
def peek (self ):
if not self .is_empty ():
return self .items [-1 ]
def is_empty (self ):
return len (self .items ) == 0
s = Stack ()
s .push (1 )
s .push (2 )
s .push (3 )
print (s .pop ())
print (s .peek ())
Copy
Run
Explain
Line-by-line explanation
Line Explanation
class Stack:Stack class using list as underlying storage
def push(self, item):Adds item to top (end of list)
self.items.append(item)Appends to list
def pop(self):Removes and returns top item
return self.items.pop()Removes last element (LIFO)
def peek(self):Returns top item without removing
return self.items[-1]Accesses last element
s.push(1); s.push(2); s.push(3)Stack: [1, 2, 3]
s.pop()Returns 3 (last in, first out)
s.peek()Returns 2 (top of stack after pop)
stack LIFO
Queue (FIFO) with deque
Queue implementation using collections.deque for efficient append and popleft operations.
from collections import deque
queue = deque ()
queue .append ("first" )
queue .append ("second" )
queue .append ("third" )
print (queue .popleft ())
print (queue .popleft ())
print (queue )
Copy
Run
Explain
Line-by-line explanation
Line Explanation
from collections import dequeImports deque for efficient queue operations
queue = deque()Creates an empty deque
queue.append("first")Adds to right end (enqueue)
queue.popleft()Removes from left end (dequeue) → "first"
queue.popleft()Removes next → "second"
print(queue)Remaining queue: deque(['third'])
queue deque
Binary Tree Traversal (In-order)
Recursive tree traversal implementing in-order: left, root, right.
class TreeNode :
def __init__ (self , val ):
self .val = val
self .left = None
self .right = None
def inorder (root ):
if root is None :
return []
return inorder (root .left ) + [root .val ] + inorder (root .right )
root = TreeNode (1 )
root .left = TreeNode (2 )
root .right = TreeNode (3 )
root .left .left = TreeNode (4 )
root .left .right = TreeNode (5 )
print (inorder (root ))
Copy
Run
Explain
Line-by-line explanation
Line Explanation
class TreeNode:Binary tree node with left and right children
def inorder(root):Recursive in-order traversal function
if root is None: return []Base case: empty tree
return inorder(root.left) + [root.val] + inorder(root.right)Visits left subtree, then root, then right subtree
Tree built: 1 (left:2 with children 4,5; right:3) Creates sample binary tree
print(inorder(root))Outputs [4, 2, 5, 1, 3]
binary tree traversal recursion
Memoized Fibonacci (Dynamic Programming)
Efficient recursion with caching using lru_cache for O(n) performance.
from functools import lru_cache
@lru_cache (maxsize =None )
def fib (n ):
if n < 2 :
return n
return fib (n -1 ) + fib (n -2 )
print ([fib (i ) for i in range (10 )])
Copy
Run
Explain
Line-by-line explanation
Line Explanation
from functools import lru_cacheImports LRU cache decorator
@lru_cache(maxsize=None)Caches all results (unbounded cache)
def fib(n):Recursive Fibonacci with memoization
if n < 2: return nBase cases: fib(0)=0, fib(1)=1
return fib(n-1) + fib(n-2)Recursive step (cached results prevent exponential time)
[fib(i) for i in range(10)]Outputs: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
DP memoization fibonacci
🏁 What's Next After Mastering These Snippets?
You've now explored the most important Python concepts through 40+ curated code snippets with detailed explanations. This library is designed to be your go-to reference as you continue your Python journey.
🚀 Why Every Programmer Should Master These Concepts
Python is the language of AI and Data Science – These snippets build the foundation for machine learning, data analysis, and artificial intelligence
Python powers modern web development – Understanding these fundamentals is essential for Flask, Django, and FastAPI
Python automates the world – From simple scripts to complex automation pipelines, these patterns appear everywhere
Python is the most in-demand skill – Companies across every industry seek Python developers
These patterns transfer to other languages – Mastering Python's approach to OOP, algorithms, and data structures makes learning any other language easier
📚 How to Continue Your Learning
Practice daily – Write code every day, even if it's just 15 minutes
Build projects – Apply these snippets to real problems you care about
Contribute to open source – Start with documentation or small bug fixes
Join the community – Engage with other Python developers on Discord, Reddit, or local meetups
Never stop learning – Python evolves rapidly; stay current with new features in 3.12 and beyond
🐍 Keep coding, keep building, keep growing. The Python community is waiting for you.
Poetic Bytes · 2026 · Made with ❤️ by Glenn Junsay Pansensoy