🐍 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
variablesdynamic typingassignment

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])
stringsf-stringsslicingjoin

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)
numbersmathoperators
🔄 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)
if/elif/elseternary

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=" ")
for loopsrangeenumerate

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
while loopsbreak

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})")
matchpattern 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)
listscomprehensionssort

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
dictionariesdefaultdictcomprehensions

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)}
setsunionintersection

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
tuplesunpackingnamedtuple
🛠️ 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)
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"])
lambdamapfilter

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"
decoratorstiming
🏗️ 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))
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())
inheritancesuperpolymorphism

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)
@propertygettersetter

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)
dataclassboilerplate
⚡ 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=" ")
generatorsyield

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!")
context managerwith

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())
asyncawaitasyncio

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
type hintstyping
🧮 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))
binary searchalgorithm

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))
quicksortsorting

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))
recursionfactorial

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)
singletondesign 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")
file I/Oreadwrite

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)
jsondumpsloads

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']}")
csvDictReader

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)
pathlibPath
🧪 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")
exceptionstry/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()
testingpytestassert
🧰 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)
datetimestrftime

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)
randomrandint

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")
collectionsCounterdefaultdict

itertools

Efficient looping with combinatoric iterators.

import itertools

perms = list(itertools.permutations([1, 2, 3], 2))
print(perms[:3])
itertoolspermutations

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)
regexre
📦 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())
linked listdata 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())
stackLIFO

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)
queuedeque

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))
binary treetraversalrecursion

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)])
DPmemoizationfibonacci

🏁 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

Python Output