Reference library

Python Code Samples

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

7 matches
Algorithms & data structures easy

How to Generate Fibonacci Sequence in Python

Generate the first n Fibonacci numbers as a list using a simple iterative loop.

fibonacci sequences iteration
Python
def fibonacci(n):
    """Generate the first n terms of the Fibonacci sequence."""
    if n <= 0:
        return []
    seq = [0, 1]
    while len(seq) < n:
        seq.append(seq[-1] + seq[-2])
    return seq[:n]

if __name__ == "__main__":
    n = 10
    result = fibonacci(n)
    print(result)
13 0 Open
Algorithms & data structures easy

How to Generate an Arithmetic Progression List in Python

Generates a list of terms in an arithmetic progression using a list comprehension.

arithmetic list-comprehension sequences
Python
def generate_ap(start, difference, count):
    """Generate a list of n terms in an arithmetic progression."""
    return [start + i * difference for i in range(count)]


if __name__ == "__main__":
    ap = generate_ap(3, 5, 6)
    print(ap)
14 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 Reset Python's Random Seed for Deterministic Output

This code shows how to seed Python's random module to generate identical random sequences across runs, ensuring reproducibility.

random seeding deterministic
Python
import random

def seeded_random_sequence(seed, count=5, low=1, high=100):
    random.seed(seed)
    return [random.randint(low, high) for _ in range(count)]

if __name__ == "__main__":
    seed_value = 42
    first_run = seeded_random_sequence(seed_value)
    print("First run:", first_run)

    # Reset seed and gener…
12 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
Testing & modern typing easy

How to Sort Data in Python

Sort sequences with type-safe helpers that handle mixed data with a string fallback.

sorting typing protocol
Python
from typing import Any, TypeVar, Protocol, Sequence, Iterable

T = TypeVar("T")
Comparable = TypeVar("Comparable", bound="Comparable")

class Sortable(Protocol):
    def __lt__(self, other: Any) -> bool: ...

S = TypeVar("S", bound=Sortable)

def sort_data(data: Sequence[S], *, reverse: bool = False) -> list[S]:
    "…
14 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.