Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

1685 matches
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

Find Most Active Contributors in a Repository with Python

Filter recent commits by date and count the most active contributors using Counter and datetime.

collections datetime counter
Python
from collections import Counter
from datetime import datetime, timedelta

# Simulated commit data
commits = [
    {"author": "Alice", "timestamp": datetime.now() - timedelta(days=1)},
    {"author": "Bob", "timestamp": datetime.now() - timedelta(days=2)},
    {"author": "Alice", "timestamp": datetime.now() - timedelta…
45 0 Open
Lists & loops easy

Format Lists of Tuples into Numbered Lines in Python

This code loops through a list of (name, grade) tuples and formats each into a numbered line using enumerate and f-strings.

enumerate formatting lists
Python
def format_students(students):
    formatted = []
    for i, student in enumerate(students, start=1):
        name, grade = student
        formatted.append(f"{i}. {name}: {grade}")
    return "\n".join(formatted)


if __name__ == "__main__":
    students = [
        ("Alice", 92),
        ("Bob", 85),
        ("Charl…
15 0 Open
Lists & loops easy

Generate Data Helper for Beginners in Python

Define two functions that create a random list of integers and then compute basic summary statistics like count, total, average, maximum, and minimum using simple loops.

random loops lists
Python
from random import randint

def build_dataset(size: int, max_val: int) -> list[int]:
    data = []
    for _ in range(size):
        data.append(randint(1, max_val))
    return data

def summarize(data: list[int]) -> dict[str, float]:
    total = 0
    maximum = data[0]
    minimum = data[0]
    for value in data:
   …
12 0 Open
Lists & loops easy

How to Build a Frequency Map from a List in Python

This code builds a dictionary that maps each unique element in a list to its count using the Counter class from the collections module.

counter frequency dictionary
Python
from collections import Counter

def build_frequency_map(values):
    """Return a dictionary mapping each unique value to its frequency."""
    return dict(Counter(values))

if __name__ == "__main__":
    data = ["apple", "banana", "apple", "cherry", "banana", "apple"]
    freq_map = build_frequency_map(data)
    prin…
13 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 Build a Text Processor with Lists and Loops in Python

A beginner-friendly Python script that analyzes text by counting sentences, words, and word lengths using lists and for loops, then prints the results.

text-processing loops lists
Python
def process_text(text):
    """Simple text processor for beginners using lists and loops."""
    sentences = text.replace('!', '.').replace('?', '.').split('.')
    words = text.split()
    
    word_counts = []
    for sentence in sentences:
        sentence_word_count = len(sentence.split())
        word_counts.appe…
12 0 Open
Lists & loops easy

How to Calculate a Cumulative Sum in Python

Build a new list where each element equals the running total of all numbers up to that index in the original list.

lists cumulative-sum loops
Python
numbers = [1, 2, 3, 4, 5]
cumulative_sum = []
running_total = 0

for num in numbers:
    running_total += num
    cumulative_sum.append(running_total)

print(cumulative_sum)
12 0 Open
Lists & loops easy

How to Calculate the Average of a List of Numbers in Python

Compute the arithmetic mean of a numeric list using Python's built-in sum() and len() functions, returning 0.0 for an empty list.

average mean sum
Python
def calculate_average(numbers):
    if not numbers:
        return 0.0
    return sum(numbers) / len(numbers)

if __name__ == "__main__":
    sample_numbers = [10, 20, 30, 40, 50]
    result = calculate_average(sample_numbers)
    print(f"Average: {result}")
13 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 Check if a List is Sorted in Descending Order in Python

This code defines a function that returns True if a given list is sorted in descending order, using a generator expression with all() to compare each adjacent pair.

sorted descending list
Python
def is_descending(lst):
    """Return True if list is sorted in descending order."""
    return all(lst[i] >= lst[i + 1] for i in range(len(lst) - 1))


if __name__ == "__main__":
    test_cases = [
        [5, 4, 3, 2, 1],
        [3, 3, 2, 1],
        [1, 2, 3],
        [10, 8, 9],
        []
    ]

    for case in …
13 0 Open
Lists & loops easy

How to Compute a Moving Average in Python

This code computes the moving average over a numeric list using an efficient sliding window sum, avoiding recomputation of each window.

moving-average sliding-window lists
Python
def moving_average(data, window_size):
    """
    Compute the moving average over a numeric list.
    
    Args:
        data: List of numeric values
        window_size: Size of the sliding window (positive integer)
    
    Returns:
        List of moving averages, each representing the mean of a window
    """
   …
14 0 Open
Lists & loops easy

How to Count Occurrences of a Value in a Python List

Counts how many times a specific value appears in a list using a simple loop and a counter variable.

counting loops lists
Python
def count_occurrences(data, target):
    count = 0
    for item in data:
        if item == target:
            count += 1
    return count


if __name__ == "__main__":
    numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
    target_value = 5
    result = count_occurrences(numbers, target_value)
    print(f"The value {targ…
13 0 Open
Lists & loops easy

How to Count, Double, and Find Max in a Python List

Three beginner-friendly Python functions that count even numbers, double each value, and find the maximum in a list using simple loops.

lists loops beginner
Python
def count_even_numbers(numbers):
    """Return the count of even numbers in a list."""
    count = 0
    for num in numbers:
        if num % 2 == 0:
            count += 1
    return count


def double_values(numbers):
    """Return a new list with each value doubled."""
    doubled = []
    for num in numbers:
     …
14 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 Filter Empty Strings in Python

Remove empty and whitespace-only strings from a list using a list comprehension with the strip() method.

filtering strings list-comprehension
Python
def filter_empty_strings(strings):
    """
    Filter out empty strings (including whitespace-only strings)
    from a list of strings.
    """
    return [s for s in strings if s.strip()]


if __name__ == "__main__":
    sample_list = ["hello", "", "world", "   ", "python", " ", "!"]
    filtered = filter_empty_strin…
12 0 Open
Lists & loops easy

How to Filter Even Numbers and Square Them in Python

Create two beginner-friendly helper functions that filter even numbers and compute squares of a number list using loops, then print the results along with the sum and average.

loops filtering math
Python
def get_even_numbers(numbers):
    evens = []
    for num in numbers:
        if num % 2 == 0:
            evens.append(num)
    return evens

def get_squares(numbers):
    squares = []
    for num in numbers:
        squares.append(num ** 2)
    return squares

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_numbers …
15 0 Open
Lists & loops easy

How to Filter None Values from a Mixed List in Python

Filter None values from a mixed Python list using a list comprehension with the `is not None` condition.

filter list-comprehension none
Python
mixed_list = [1, None, "hello", None, 3.14, None, [1, 2], None]

filtered_list = [item for item in mixed_list if item is not None]

print(f"Original list: {mixed_list}")
print(f"Filtered list: {filtered_list}")
print(f"Original length: {len(mixed_list)}, Filtered length: {len(filtered_list)}")
15 0 Open
Lists & loops easy

How to Filter a List in Python with a Loop

Filter a list of numbers by a threshold using a for loop and append results to a new list, then print the filtered values and count.

filter for-loop lists
Python
ages = [34, 12, 45, 8, 67, 21, 18, 55, 3]
threshold = 18

adults = []
for age in ages:
    if age >= threshold:
        adults.append(age)

print("All ages:", ages)
print("Adults (18+):", adults)
print("Count of adults:", len(adults))
10 0 Open
Lists & loops easy

How to Find Local Maxima in a Python List

Return the indices of all local maxima in a numeric list, where a peak is an element greater than both its immediate neighbors.

local-maxima peaks list
Python
def find_peaks(numbers):
    """
    Return the indices of local maxima in a numeric list.
    A local maximum is an element greater than both its neighbors.
    """
    if len(numbers) < 3:
        return []
    
    peaks = []
    for i in range(1, len(numbers) - 1):
        if numbers[i] > numbers[i - 1] and number…
15 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 Find the Mode in a Python List

Find the most frequent value (mode) in a Python list using the collections.Counter class, handling empty lists and ties.

mode counter frequency
Python
from collections import Counter

def find_mode(numbers):
    if not numbers:
        return None
    counts = Counter(numbers)
    max_count = max(counts.values())
    modes = [num for num, count in counts.items() if count == max_count]
    return modes[0] if len(modes) == 1 else modes

if __name__ == "__main__":
    …
14 0 Open
Lists & loops easy

How to Find the Third Smallest Element in a Python List

Find the third smallest distinct value in a Python list by sorting unique elements and returning the third index.

sorting lists unique
Python
def find_third_smallest(numbers):
    if len(numbers) < 3:
        return None
    
    unique_sorted = sorted(set(numbers))
    
    if len(unique_sorted) < 3:
        return None
    
    return unique_sorted[2]


if __name__ == "__main__":
    sample = [5, 2, 8, 2, 9, 1, 7, 3]
    result = find_third_smallest(sampl…
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

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.