Reference library

Python Code Samples

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

34 matches
Lists & loops easy

Enumerate a Python List with a Custom Start Index

Iterate over a list with an index that starts at a custom value (like 5) using Python's built-in enumerate() function with the start parameter.

enumerate iteration loops
Python
fruits = ["apple", "banana", "cherry", "date"]

for index, fruit in enumerate(fruits, start=5):
    print(f"{index}: {fruit}")
15 0 Open
Lists & loops easy

Find Maximum Value in a List of Numbers in Python

Iterate through a list with a for loop to manually find and return the maximum numeric value.

max list loop
Python
def find_max(numbers):
    """Return the maximum value in a list of numbers."""
    if not numbers:
        return None
    max_value = numbers[0]
    for num in numbers[1:]:
        if num > max_value:
            max_value = num
    return max_value

if __name__ == "__main__":
    sample_list = [3, 7, 2, 15, 9, 11]
…
15 0 Open
Lists & loops easy

Find Minimum Value in a List in Python

This code defines a function that finds and returns the minimum value in a list of numbers, handling empty lists gracefully by returning None.

minimum lists iteration
Python
def find_minimum(numbers):
    """
    Find and return the minimum value in a list of numbers.
    
    Args:
        numbers: List of numeric values
        
    Returns:
        The minimum value, or None if the list is empty
    """
    if not numbers:
        return None
    min_value = numbers[0]
    for num in n…
12 0 Open
Lists & loops easy

How to Build a Running Maximum List in Python

Compute a list where each element is the maximum of all numbers seen so far from an input list.

running-max iteration lists
Python
def running_maximum(numbers):
    result = []
    current_max = float('-inf')
    for num in numbers:
        if num > current_max:
            current_max = num
        result.append(current_max)
    return result

if __name__ == "__main__":
    numbers = [3, 1, 4, 1, 5, 9, 2, 6]
    max_list = running_maximum(number…
15 0 Open
Lists & loops easy

How to Calculate the Sum of List Elements in Python

Iterates over a list with a for loop, accumulates each number into a total variable, and returns the sum of all elements.

sum list loop
Python
def sum_list_elements(numbers):
    """Return the sum of all elements in a list."""
    total = 0
    for num in numbers:
        total += num
    return total

if __name__ == "__main__":
    sample_list = [1, 2, 3, 4, 5]
    result = sum_list_elements(sample_list)
    print(f"The sum of {sample_list} is {result}")
13 0 Open
Lists & loops easy

How to Cycle Through a List Infinitely with itertools

This code uses itertools.cycle to create an infinite iterator over a list and returns the first n items from that cycle.

itertools cycle infinite iteration
Python
from itertools import cycle

def demonstrate_cycle(items, cycles=3):
    """
    Cycle through a list infinitely using itertools.cycle.
    Returns the first n items from the infinite cycle.
    """
    cycled = cycle(items)
    result = [next(cycled) for _ in range(len(items) * cycles)]
    return result

if __name__…
14 0 Open
Lists & loops easy

How to Find the Maximum Value in a Python List

This code defines a function that finds the largest number in a list by iterating through it, returning None for an empty list, and demonstrates it on a sample list.

max list loop
Python
def find_max(numbers):
    if not numbers:
        return None
    max_value = numbers[0]
    for num in numbers[1:]:
        if num > max_value:
            max_value = num
    return max_value

if __name__ == "__main__":
    sample_list = [3, 7, 2, 9, 1, 9]
    result = find_max(sample_list)
    print(f"Maximum valu…
15 0 Open
Lists & loops easy

How to Flatten One Level of a Nested List in Python

Flattens exactly one level of a nested list by extending the output with each inner list and appending non-list items.

flatten nested list list comprehension
Python
def flatten_one_level(nested_list):
    """Flatten one level of a nested list."""
    flattened = []
    for item in nested_list:
        if isinstance(item, list):
            flattened.extend(item)
        else:
            flattened.append(item)
    return flattened

if __name__ == "__main__":
    # Example with mi…
15 0 Open
Lists & loops easy

How to Loop Through Lists in Python for Beginners

Transform, filter, sum, and find the maximum in a Python list using basic for loops and conditionals.

lists loops iteration
Python
def transform_data(numbers):
    """Basic transformation examples using lists and loops."""
    doubled = []
    for n in numbers:
        doubled.append(n * 2)
    return doubled


def filter_even(numbers):
    """Keep only even numbers using a loop and condition."""
    evens = []
    for n in numbers:
        if n …
15 0 Open
Functions & basics easy

Chain Generators with yield from in Python

Combine multiple generators into one seamless sequence using the `yield from` delegation syntax in Python.

generators yield delegation
Python
def numbers():
    yield 1
    yield 2
    yield 3

def letters():
    yield 'a'
    yield 'b'
    yield 'c'

def combined():
    yield from numbers()
    yield from letters()

if __name__ == "__main__":
    print(list(combined()))
16 0 Open
Functions & basics easy

How to Convert a List to an Iterator in Python with iter()

This code converts a list into an iterator using the built-in iter() function and retrieves items sequentially with next(), handling exhaustion with StopIteration.

iter iterator built-in
Python
def main():
    # Original list
    fruits = ["apple", "banana", "cherry"]

    # Convert the list to an iterator using iter()
    fruit_iterator = iter(fruits)

    # Retrieve items one at a time with next()
    print(next(fruit_iterator))  # apple
    print(next(fruit_iterator))  # banana
    print(next(fruit_iterat…
12 0 Open
Functions & basics easy

How to Create Generator Functions with yield in Python

Create a memory-efficient generator function using yield to produce a Fibonacci sequence up to a limit.

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


if __name__ == "__main__":
    fib_gen = fibonacci_sequence(100)
    
    for number in fib_gen:
        print(number, end=" ")
    print()
11 0 Open
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(…
15 0 Open
Algorithms & data structures easy

Drop Elements From Start While Condition Is True in Python

This generator function drops elements from the beginning of an iterable while a predicate returns true, then yields the rest.

generator iteration filtering
Python
def drop_while(predicate, iterable):
    """Drop elements from the start while predicate is true."""
    it = iter(iterable)
    for item in it:
        if not predicate(item):
            yield item
            break
    yield from it

if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 1, 2, 5]
    result = list(d…
12 0 Open
Algorithms & data structures easy

How to Find Gaps Between Sorted Intervals in Python

This code finds gap ranges between sorted intervals using pairwise iteration, returning ranges where no interval covers.

intervals pairwise sorting
Python
from itertools import pairwise

def find_gaps(intervals):
    intervals = sorted(intervals)
    gaps = []
    for prev, curr in pairwise(intervals):
        if prev[1] < curr[0]:
            gaps.append((prev[1] + 1, curr[0] - 1))
    return gaps

if __name__ == "__main__":
    intervals = [(1, 3), (5, 7), (10, 12), (…
14 0 Open
Algorithms & data structures easy

How to Flatten List of Dict Values in Python

This code flattens the values of a list of dictionaries into a single list, handling both list values and scalar values.

flatten dictionaries lists
Python
def flatten_dict_values(dicts):
    flattened = []
    for d in dicts:
        for value in d.values():
            if isinstance(value, list):
                flattened.extend(value)
            else:
                flattened.append(value)
    return flattened


if __name__ == "__main__":
    data = [
        {"a": …
12 0 Open
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

Take While Predicate True From Start in Python

Create a custom take_while function that collects elements from an iterable until a predicate returns False, then stops.

takewhile iteration predicate
Python
def take_while(predicate, iterable):
    """Return elements from iterable until the predicate becomes False."""
    result = []
    for item in iterable:
        if predicate(item):
            result.append(item)
        else:
            break
    return result


if __name__ == "__main__":
    numbers = [2, 4, 6, 7,…
13 0 Open
Comprehensions & generators easy

Batch Rows in Chunks with a Generator in Python

Group a list of row dicts into fixed-size chunks using a generator that yields one slice per call.

generators chunking database
Python
from typing import Iterator, List


def batch_rows(rows: List[dict], batch_size: int) -> Iterator[List[dict]]:
    for i in range(0, len(rows), batch_size):
        yield rows[i:i + batch_size]


if __name__ == "__main__":
    sample_rows = [
        {"id": 1, "name": "Alice"},
        {"id": 2, "name": "Bob"},
      …
15 0 Open
Comprehensions & generators easy

Cycle an iterable forever in Python

Define a generator that repeatedly yields items from an iterable, cycling back to the beginning infinitely.

generators cycle iteration
Python
def cycle_generator(iterable):
    """Yield items from iterable forever, cycling back to the start."""
    items = list(iterable)  # Convert to list so it can restart
    index = 0
    while True:
        yield items[index]
        index = (index + 1) % len(items)


if __name__ == "__main__":
    colors = ["red", "gre…
14 0 Open
Comprehensions & generators easy

Enumerate a Generator With a Running Total in Python

A generator that yields each element with its index and a cumulative sum, letting you track a running total as you iterate.

generators enumerate running-total
Python
def running_total_enum(iterable):
    """Yields (index, item, running_total) for each element."""
    total = 0
    for index, item in enumerate(iterable):
        total += item
        yield index, item, total

if __name__ == "__main__":
    numbers = [10, 20, 30, 40, 50]
    for idx, value, running_sum in running_to…
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

Group Consecutive Keys in Python with itertools.groupby

Group consecutive equal elements in a list using the itertools.groupby generator, printing each key and its values.

itertools groupby generators
Python
from itertools import groupby

data = [1, 1, 2, 2, 3, 1, 1, 4, 4, 4]

for key, group in groupby(data):
    group_list = list(group)
    print(f"Key: {key}, Values: {group_list}")
11 0 Open
Comprehensions & generators easy

How to Accumulate Values with a Generator in Python

This generator yields the running total of an iterable's elements, producing a cumulative sum with each step.

generator accumulate cumulative-sum
Python
def accum(iterable):
    total = 0
    for item in iterable:
        total += item
        yield total

# Demo
if __name__ == "__main__":
    data = [1, 2, 3, 4, 5]
    print(list(accum(data)))  # [1, 3, 6, 10, 15]

    # Also works with any iterable, e.g., range
    print(list(accum(range(1, 6))))  # [1, 3, 6, 10, 15]
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.