Reference library

Python Code Samples

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

411 matches
Lists & loops easy

How to Sort a List of Dictionaries by a Key in Python

Sort a list of dictionaries by a specified key field, optionally in descending order, using Python's built-in sorted() function.

sort dictionaries list
Python
def sort_dicts_by_key(data, key, reverse=False):
    return sorted(data, key=lambda item: item.get(key), reverse=reverse)


if __name__ == "__main__":
    people = [
        {"name": "Alice", "age": 30},
        {"name": "Bob", "age": 25},
        {"name": "Charlie", "age": 35},
    ]

    sorted_by_age = sort_dicts_b…
14 0 Open
Lists & loops easy

How to Sort a List of Tuples by the Second Element in Python

Sorts a list of tuples by the second element using the sorted() function with a lambda key, preserving the original list.

sorting tuples lambda
Python
def sort_tuples_by_second(tuples_list):
    """Sort a list of tuples by the second element."""
    return sorted(tuples_list, key=lambda x: x[1])


if __name__ == "__main__":
    data = [(1, 5), (3, 2), (2, 8), (4, 1)]
    sorted_data = sort_tuples_by_second(data)
    print("Original list:", data)
    print("Sorted by…
13 0 Open
Lists & loops easy

How to Split a List at the First Occurrence of a Value in Python

This function splits a list into two parts at the first occurrence of a given value, returning the left and right portions.

list slicing split
Python
def split_at_first(lst, value):
    try:
        idx = lst.index(value)
        return lst[:idx], lst[idx:]
    except ValueError:
        return lst, []

if __name__ == "__main__":
    sample = [1, 2, 3, 4, 3, 5]
    value = 3
    left, right = split_at_first(sample, value)
    print("Left:", left)
    print("Right:"…
13 0 Open
Lists & loops easy

How to Split a List into Chunks in Python

Split a list into fixed-size sublists using a simple list comprehension with slicing.

list slicing chunking
Python
def chunk_list(lst, size):
    """Split a list into sublists of given size."""
    return [lst[i:i + size] for i in range(0, len(lst), size)]


if __name__ == "__main__":
    sample = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    print(chunk_list(sample, 3))
13 0 Open
Lists & loops easy

How to Standardize a List with Z-Score Normalization in Python

This code computes the z-score for each number in a list, standardizing the data to have zero mean and unit variance using the statistics module.

z-score standardization statistics
Python
import statistics

def z_score_normalize(values):
    """Standardize a list of numbers using z-score normalization."""
    if not values or len(values) < 2:
        raise ValueError("Need at least 2 values for meaningful z-score normalization")
    
    mean = statistics.mean(values)
    std_dev = statistics.stdev(val…
14 0 Open
Lists & loops easy

How to Summarize a List of Numbers in Python

Loop over a list of numbers to compute total, count, average, min, and max, then return them in a dictionary.

lists loops statistics
Python
def summarize_numbers(numbers):
    """Return a dict with basic stats for a list of numbers."""
    total = 0
    count = 0
    smallest = numbers[0]
    largest = numbers[0]

    for num in numbers:
        total += num
        count += 1
        if num < smallest:
            smallest = num
        if num > largest:…
16 0 Open
Lists & loops easy

How to Swap Two Indices in a Python List

Swap two elements at given indices in a Python list using simultaneous assignment, then return the modified list.

list swap indexing
Python
def swap_indices(lst, i, j):
    lst[i], lst[j] = lst[j], lst[i]
    return lst

if __name__ == "__main__":
    my_list = [10, 20, 30, 40, 50]
    print("Original list:", my_list)
    swapped = swap_indices(my_list, 1, 3)
    print("After swapping indices 1 and 3:", swapped)
14 0 Open
Lists & loops easy

How to Transpose a Matrix in Python (List of Lists)

Swap rows and columns of a 2D list using nested loops to produce a transposed matrix.

matrix transpose 2d-list
Python
def transpose(matrix):
    # Number of rows and columns in the original matrix
    rows = len(matrix)
    cols = len(matrix[0]) if rows > 0 else 0
    
    # Create a new matrix with dimensions swapped
    result = []
    for j in range(cols):
        new_row = []
        for i in range(rows):
            new_row.appe…
13 0 Open
Lists & loops easy

How to Truncate a List to Max Length in Python (Keep Head)

This code returns a new list containing only the first max_length items from the original list, using Python's slice syntax.

list slicing truncate
Python
from typing import List

def truncate_head(lst: List[object], max_length: int) -> List[object]:
    """Return a new list with at most max_length items from the head."""
    if max_length < 0:
        raise ValueError("max_length must be non-negative")
    return lst[:max_length]

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

How to Validate List Data in Python

A beginner-friendly validation helper that checks if data is a list, enforces minimum length, and optionally verifies item types with clear error messages.

validation lists loops
Python
def validate_data(data, expected_types=None, min_length=1):
    """Validate that data is a non-empty list and optionally check item types."""
    if not isinstance(data, list):
        return False, f"Expected a list, got {type(data).__name__}"
    
    if len(data) < min_length:
        return False, f"List must have…
16 0 Open
Lists & loops easy

How to Validate Text Against Forbidden Words in Python

Checks whether a given text contains any forbidden words and returns a tuple with validity and offending words.

text validation lists loops
Python
def validate_text(text, forbidden_words):
    """
    Checks that text does not contain any forbidden words.
    Returns (is_valid, offending_words) tuple.
    """
    words = text.lower().split()
    found = [word for word in words if word in forbidden_words]
    return len(found) == 0, found


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

How to Zip Two Lists into Pairs in Python

Combine two lists element-wise into a list of tuples using Python's built-in zip() function.

zip lists tuples
Python
def zip_lists_into_pairs(list1, list2):
    pairs = list(zip(list1, list2))
    return pairs

if __name__ == "__main__":
    fruits = ["apple", "banana", "cherry"]
    quantities = [3, 5, 2]
    result = zip_lists_into_pairs(fruits, quantities)
    print(result)
14 0 Open
Lists & loops easy

How to check list items by type and emptiness in Python

Loop through a list with enumerate(), classify each item as empty, number, or text, and print a formatted status for each element.

lists loops enumerate
Python
def check_data(data):
    """Check each item in a list and print whether it's valid."""
    for i, item in enumerate(data):
        if item is None or item == "":
            status = "empty"
        elif isinstance(item, (int, float)):
            status = "number"
        else:
            status = "text"
        pr…
14 0 Open
Lists & loops easy

How to split a list by condition in Python

Splits a list into two lists based on a condition function, returning matched and unmatched items.

lists condition partition
Python
def split_by_condition(items, condition):
    """
    Split a list into two lists based on a condition.
    The first list contains items where condition(item) is True,
    the second list contains the rest.
    """
    matched = []
    unmatched = []
    for item in items:
        if condition(item):
            matc…
11 0 Open
Lists & loops easy

How to summarize and transform lists in Python

Compute count, sum, min, max, and average for a list and multiply each element by a factor using simple loops and built-in functions.

lists loops statistics
Python
def summarize(data):
    """Return a summary of a list: count, sum, min, max, average."""
    count = len(data)
    total = sum(data)
    minimum = min(data)
    maximum = max(data)
    average = total / count if count else 0
    return count, total, minimum, maximum, average


def multiply_elements(data, factor=2):
 …
13 0 Open
Lists & loops easy

How to unzip a list of pairs into two lists in Python

Split a list of (a, b) tuples into two separate lists by iterating with a for loop and appending each element to its own output list.

lists tuples loops
Python
def unzip(pairs):
    """Split a list of (a, b) pairs into two separate lists."""
    if not pairs:
        return [], []
    
    firsts = []
    seconds = []
    for a, b in pairs:
        firsts.append(a)
        seconds.append(b)
    
    return firsts, seconds


if __name__ == "__main__":
    pairs = [(1, 'a'), (…
14 0 Open
Lists & loops easy

Intersection of Two Lists Preserving Order in Python

This code returns the common elements between two lists while preserving the order they appear in the first list, filtering out duplicates.

lists intersection order
Python
def intersection_preserving_order(list1, list2):
    """
    Return the intersection of two lists while preserving the order
    of elements as they appear in list1.
    """
    set2 = set(list2)
    result = []
    seen = set()
    
    for item in list1:
        if item in set2 and item not in seen:
            resu…
15 0 Open
Lists & loops easy

Pairwise Adjacent Differences in a Python List

Computes the absolute differences between each pair of adjacent elements in a list using a concise list comprehension.

list-comprehension differences absolute-value
Python
def adjacent_differences(nums):
    """Return list of absolute differences between adjacent elements."""
    return [abs(nums[i] - nums[i + 1]) for i in range(len(nums) - 1)]


if __name__ == "__main__":
    sample = [3, 7, 2, 9, 5]
    diffs = adjacent_differences(sample)
    print("Original list:", sample)
    print…
14 0 Open
Lists & loops easy

Replace Negative Values in a List with Python

This code defines a function that replaces every negative number in a list with a replacement value, defaulting to zero, using a list comprehension.

list-comprehension data-cleaning list-transformation
Python
def replace_if_negative(values, replacement=0):
    return [replacement if value < 0 else value for value in values]

if __name__ == "__main__":
    numbers = [5, -3, 8, -1, 0, -7, 2]
    result = replace_if_negative(numbers)
    print(f"Original: {numbers}")
    print(f"Replaced: {result}")
14 0 Open
Lists & loops easy

Rotate List Left by k Positions in Python

Rotates a list left by k positions using slicing and modulo arithmetic to handle large k safely.

list rotation slicing
Python
def rotate_left(lst, k):
    if not lst:
        return []
    k = k % len(lst)
    return lst[k:] + lst[:k]

if __name__ == "__main__":
    my_list = [1, 2, 3, 4, 5]
    k = 2
    result = rotate_left(my_list, k)
    print(f"Original: {my_list}")
    print(f"After rotating left by {k}: {result}")
13 0 Open
Lists & loops easy

Round Robin Merge Multiple Lists in Python

Merge multiple lists by taking one element from each in turn, stopping when all lists are exhausted.

lists merge interleave
Python
from itertools import cycle

def round_robin_merge(*lists):
    """Merge multiple lists by taking one element from each in turn."""
    result = []
    max_len = max(len(lst) for lst in lists)
    
    for i in range(max_len):
        for lst in lists:
            if i < len(lst):
                result.append(lst[i])…
14 0 Open
Lists & loops easy

Separate Evens and Odds into Two Lists in Python

Split a list of numbers into two lists containing even and odd numbers using a simple loop and the modulo operator.

lists loops modulo
Python
def separate_evens_odds(numbers):
    evens = []
    odds = []
    for num in numbers:
        if num % 2 == 0:
            evens.append(num)
        else:
            odds.append(num)
    return evens, odds

if __name__ == "__main__":
    nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    evens, odds = separate_evens_odds(nu…
13 0 Open
Lists & loops easy

Symmetric difference between two lists in Python

Find elements present in exactly one of two lists, preserving original order, with a simple Python function.

lists sets symmetric-difference
Python
def symmetric_difference(list1, list2):
    """
    Return the symmetric difference of two lists.
    Elements present in exactly one of the lists, preserving order.
    """
    set1 = set(list1)
    set2 = set(list2)
    
    # Elements in list1 but not in list2
    diff1 = [x for x in list1 if x not in set2]
    # E…
14 0 Open
Lists & loops easy

Truncate List Keeping Last N Elements in Python

Return a new list containing only the last N elements from a sequence, handling edge cases like zero or oversized counts.

list slicing sequence
Python
def truncate(seq, keep_last_n):
    """Return a new list keeping only the last n elements."""
    if keep_last_n <= 0:
        return []
    return list(seq)[-keep_last_n:]


if __name__ == "__main__":
    data = [10, 20, 30, 40, 50, 60]
    print(truncate(data, 3))
    print(truncate(data, 0))
    print(truncate(data…
11 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.