Reference library

Python Code Samples

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

5 matches
Functions & basics easy

How to Create an Iterator Class with Dunder Methods in Python

A minimal Counter class implementing __iter__ and __next__ to act as a self-iterating iterator, yielding numbers from start to end-1.

iterators dunder-methods class
Python
class Counter:
    def __init__(self, start=0, end=5):
        self.current = start
        self.end = end

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.end:
            raise StopIteration
        value = self.current
        self.current += 1
        return val…
13 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

How to Parse CSV Rows as Generator Dicts in Python

Reads a CSV file and yields each row as a dictionary one at a time using a generator, so the file is processed lazily.

csv generator parsing
Python
import csv
from pathlib import Path

def csv_to_dicts(filepath):
    with open(filepath, mode="r", newline="", encoding="utf-8") as file:
        reader = csv.DictReader(file)
        for row in reader:
            yield row

if __name__ == "__main__":
    sample_csv = Path("sample_data.csv")
    sample_csv.write_text…
13 0 Open
Comprehensions & generators easy

How to Repeat a Generator Cycle Single Value in Python

Build a generator that repeats a single value across multiple cycles, each cycle adding an extra repetition to mark its completion.

generators loops repeat
Python
def repeat_with_cycle(value, cycle_limit, repetitions):
    """
    Repeats a single value until reaching a cycle limit,
    then yields the value one more time to demonstrate a full cycle.
    
    Args:
        value: The single value to repeat.
        cycle_limit: Number of repetitions per cycle.
        repetitio…
13 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.