Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

21 matches
Files & data easy

How to Read a Text File Line by Line in Python

Reads a text file line by line with an enumerated for loop and prints each line number and content.

file-io text-files loops
Python
from pathlib import Path

def read_lines(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        for line_number, line in enumerate(file, start=1):
            print(f"Line {line_number}: {line.rstrip()}")

if __name__ == "__main__":
    sample_file = Path("sample.txt")
    sample_file.write_text(…
14 0 Open
Comprehensions & generators easy

Build a lazy generator to read file lines in Python

Create a generator function that yields file lines one at a time, avoiding loading the entire file into memory, and demonstrate its lazy processing.

generator file-io lazy
Python
def lazy_lines(filepath):
    """Yield lines from a file one at a time without loading the whole file into memory."""
    with open(filepath, 'r', encoding='utf-8') as file:
        for line in file:
            yield line.rstrip('\n')


if __name__ == "__main__":
    # Create a sample file to demonstrate
    sample_c…
14 0 Open
Comprehensions & generators easy

Chunk an Iterable into Batches with a Generator in Python

Yield fixed-size batches from any iterable lazily using itertools.islice inside a generator function.

generators iterators itertools
Python
from itertools import islice

def chunked(iterable, size):
    iterator = iter(iterable)
    while True:
        batch = list(islice(iterator, size))
        if not batch:
            break
        yield batch

if __name__ == "__main__":
    data = range(10)
    for batch in chunked(data, 3):
        print(batch)
14 0 Open
Comprehensions & generators easy

Drop n items then yield rest generator

A generator that skips the first n items of an iterable and then yields the remaining items one by one.

generators iterators drop
Python
def drop(n, items):
    """Yield every item except the first n from items."""
    it = iter(items)
    for _ in range(n):
        next(it, None)  # skip first n items
    yield from it


if __name__ == "__main__":
    numbers = [10, 20, 30, 40, 50]
    result = list(drop(2, numbers))
    print(result)
11 0 Open
Comprehensions & generators easy

Generate Data with Python Comprehensions and Generators

Shows list, dict compregensions and generator expressions plus a Fibonacci generator to produce data lazily.

comprehensions generators lazy-evaluation
Python
# Data generation helpers using comprehensions and generators
from itertools import islice


def fibonacci(limit):
    """Generate Fibonacci numbers up to a limit."""
    a, b = 0, 1
    while a <= limit:
        yield a
        a, b = b, a + b


def main():
    # List comprehension: squares of even numbers
    square…
15 0 Open
Comprehensions & generators easy

Generator Function to Yield an Infinite Counter in Python

This code demonstrates a generator function that yields an infinite sequence of integers starting from a given value, allowing lazy, memory-efficient iteration.

generators infinite sequences yield
Python
def infinite_counter(start=0):
    count = start
    while True:
        yield count
        count += 1

if __name__ == "__main__":
    counter = infinite_counter(5)
    for _ in range(5):
        print(next(counter))
14 0 Open
Comprehensions & generators easy

How to Create an Infinite Arithmetic Sequence Generator in Python

Build a memory-efficient generator that yields an infinite arithmetic progression and extract the first N values with list comprehension.

generators yield infinite-sequences
Python
"""Count generator infinite arithmetic progression"""


def arithmetic_counter(start=0, step=1):
    """Generate an infinite arithmetic sequence."""
    current = start
    while True:
        yield current
        current += step


if __name__ == "__main__":
    counter = arithmetic_counter(1, 3)
    result = [next(c…
14 0 Open
Comprehensions & generators easy

How to Filter Data with Predicates in Python

This helper filters a list with a predicate using a list comprehension, plus a lazy generator version that yields matches one by one.

filtering comprehensions generators
Python
def filter_data(data, predicate):
    """Return a list containing only items that pass the predicate."""
    return [item for item in data if predicate(item)]


def filter_data_lazy(data, predicate):
    """Generator version: yields items that pass the predicate one by one."""
    for item in data:
        if predicat…
16 0 Open
Comprehensions & generators easy

How to Generate Fibonacci Numbers in Python Without Recursion

Build an efficient infinite Fibonacci sequence using a generator function with O(1) memory and no recursion overhead.

generators fibonacci iteration
Python
def fib(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

if __name__ == "__main__":
    count = 10
    result = list(fib(count))
    print(result)
15 0 Open
Comprehensions & generators easy

How to Implement takewhile Generator in Python

A generator that yields items from an iterable until a condition fails, like itertools.takewhile.

generator takewhile iteration
Python
def takewhile(predicate, iterable):
    for item in iterable:
        if not predicate(item):
            break
        yield item

if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5, 1, 2, 3]
    result = list(takewhile(lambda x: x < 4, numbers))
    print(result)
13 0 Open
Comprehensions & generators easy

How to Lazily Transform Items in Python with a Generator

Map a transform function over an iterable lazily with a generator so items are processed on demand, not up front.

generators lazy evaluation mapping
Python
def lazy_map(items, transform):
    for item in items:
        yield transform(item)

def double(x):
    return x * 2

def upper(s):
    return s.upper()

if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5]
    doubled = lazy_map(numbers, double)
    print("Doubled numbers:", end=" ")
    for value in doubled:
  …
14 0 Open
Comprehensions & generators easy

How to Slice a Generator with islice in Python

Use itertools.islice to take the first n items from any iterable without materializing the whole sequence into a list.

itertools islice generators
Python
from itertools import islice


def first_n(iterable, n):
    """Return the first n items from an iterable."""
    return list(islice(iterable, n))


if __name__ == "__main__":
    numbers = range(10, 100)  # large iterable
    result = first_n(numbers, 5)
    print(result)  # [10, 11, 12, 13, 14]
14 0 Open
Comprehensions & generators easy

How to Split Data into Chunks and Use Generators in Python

Split a list into fixed-size chunks with a list comprehension and square even numbers lazily with a generator expression.

comprehensions generators chunking
Python
def split_numbers(data, chunk_size):
    return [data[i:i + chunk_size] for i in range(0, len(data), chunk_size)]


def square_even_numbers(numbers):
    return (n ** 2 for n in numbers if n % 2 == 0)


if __name__ == "__main__":
    sample_data = list(range(1, 21))
    chunks = split_numbers(sample_data, 5)
    print…
15 0 Open
Comprehensions & generators easy

How to skip items until a condition is met in Python

Use itertools.dropwhile to skip leading elements while a predicate returns true, then yield the rest of the sequence unchanged.

itertools generators dropwhile
Python
def is_negative(x):
    return x < 0

numbers = [-3, -1, 0, 5, 2, -8, 7]
result = list(itertools.dropwhile(is_negative, numbers))
print(f"Original: {numbers}")
print(f"After dropwhile: {result}")
13 0 Open
Comprehensions & generators easy

Normalize Data in Python with Comprehensions and Generators

Clean a list by dropping None values with a comprehension, then min-max normalize it using a lazy generator expression — a beginner-friendly data preparation pattern.

comprehensions generators normalization
Python
import statistics

# Sample raw data including missing and outlier-ish values
raw = [22, 18, None, 25, 30, 19, 22, 17, None, 28, 24]

# Clean the data: drop None values using a list comprehension
clean = [x for x in raw if x is not None]

# Normalize using min-max scaling with a generator expression
min_val = min(clea…
13 0 Open
Comprehensions & generators easy

Python Comprehensions and Generators for Beginners

Learn list, dict, and set comprehensions plus generator expressions and generator functions with clear, runnable examples.

comprehensions generators lazy-evaluation
Python
# Demonstrates list comprehensions, dict comprehensions, set comprehensions, and generators

def demonstrate_comprehensions():
    # List comprehension: squares of even numbers
    numbers = range(1, 11)
    even_squares = [n ** 2 for n in numbers if n % 2 == 0]
    
    # Dict comprehension: number to its factorial
 …
15 0 Open
Comprehensions & generators easy

Python Generator to Filter Duplicates with a Seen Set

A lazily-evaluated generator function that yields only the first occurrence of each item, using a set to track seen values.

generator dedupe set
Python
def unique_generator(items):
    seen = set()
    for item in items:
        if item not in seen:
            seen.add(item)
            yield item

if __name__ == "__main__":
    data = [1, 2, 2, 3, 3, 3, 4, 5, 5]
    result = list(unique_generator(data))
    print(result)
13 0 Open
Comprehensions & generators easy

Take n items from an infinite Python generator

Uses itertools.islice to lazily take exactly n items from an infinite generator without exhausting it.

generators itertools islice
Python
from itertools import islice

def count_up_from(start=0):
    n = start
    while True:
        yield n
        n += 1

def take_n(generator, count):
    return list(islice(generator, count))

if __name__ == "__main__":
    gen = count_up_from(10)
    result = take_n(gen, 5)
    print(result)
11 0 Open
Comprehensions & generators easy

Write Data Helpers with Comprehensions and Generators in Python

Demonstrates list, dict, and set comprehensions plus generator expressions and generator functions for building concise data helpers.

comprehensions generators data-helpers
Python
# Basic comprehensions and generators demo

# List comprehension: squares of evens
squares = [x * x for x in range(10) if x % 2 == 0]
print("List comp:", squares)

# Dictionary comprehension: char -> count
text = "hello"
char_counts = {c: text.count(c) for c in set(text)}
print("Dict comp:", char_counts)

# Set compre…
10 0 Open
Concurrency & performance easy

Using a Python Generator Instead of a List to Save Memory

Compare a list approach with a generator to stream values lazily, avoiding memory-heavy storage of large sequences.

generator lazy-evaluation memory
Python
def fibonacci_generator(limit):
    a, b = 0, 1
    count = 0
    while count < limit:
        yield a
        a, b = b, a + b
        count += 1


def sum_first_n(generator, n):
    total = 0
    for i, value in enumerate(generator):
        if i >= n:
            break
        total += value
    return total


if __…
12 0 Open
Microservices patterns easy

Cache-Aside Pattern in Python: Per-Service Mock

A Python mock of the cache-aside pattern for a single microservice—lazy-load from a database into an in-memory cache and invalidate on updates.

caching microservices cache-aside
Python
class ServiceCache:
    def __init__(self):
        self.database = {"user:1": "Alice", "user:2": "Bob", "user:3": "Charlie"}
        self.cache = {}

    def get_user(self, user_id):
        cache_key = f"user:{user_id}"
        if cache_key in self.cache:
            print(f"CACHE HIT: {cache_key}")
            retu…
12 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.