Reference library

Python Code Samples

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

95 matches
Lists & loops easy

How to Flatten a Deeply Nested List in Python Recursively

A recursive function that flattens arbitrarily deep nested lists into a single flat list using isinstance checks.

recursion flatten lists
Python
def flatten(nested_list):
    if not nested_list:
        return []
    if isinstance(nested_list[0], list):
        return flatten(nested_list[0]) + flatten(nested_list[1:])
    return [nested_list[0]] + flatten(nested_list[1:])


if __name__ == "__main__":
    data = [1, [2, [3, [4, [5]]]], [6, [7, [8, [9]]]], 10]
 …
13 0 Open
Lists & loops easy

How to Get the Union of Two Lists Without Duplicates in Python

Merge two lists and remove duplicate values using a set, then convert back to a list.

set union merge
Python
def union_without_duplicates(list1, list2):
    return list(set(list1 + list2))

if __name__ == "__main__":
    list_a = [1, 2, 3, 4]
    list_b = [3, 4, 5, 6]
    result = union_without_duplicates(list_a, list_b)
    print(f"Union of {list_a} and {list_b}: {result}")
13 0 Open
Lists & loops easy

How to Group Consecutive Equal Elements in Python

Group consecutive equal elements in a list into sublists using itertools.groupby.

groupby itertools lists
Python
from itertools import groupby

def group_consecutive(lst):
    """Group consecutive equal elements into sublists."""
    return [list(group) for _, group in groupby(lst)]

if __name__ == "__main__":
    input_list = [1, 1, 2, 2, 2, 3, 1, 1, 4, 4, 4, 4]
    result = group_consecutive(input_list)
    print("Input:", inp…
16 0 Open
Lists & loops easy

How to Interleave Two Lists in Python Until One List Exhausted

Interleave elements from two lists pairwise using zip, stopping when either list runs out of items.

zip lists interleave
Python
def interleave(a, b):
    result = []
    for x, y in zip(a, b):
        result.extend([x, y])
    return result

if __name__ == "__main__":
    list1 = [1, 2, 3, 4, 5]
    list2 = ["a", "b", "c"]
    print(interleave(list1, list2))
12 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
Lists & loops easy

How to Merge Two Lists in Python

Merge two Python lists into a single combined list by appending each element with a simple loop, achieving the same result as the + operator.

lists merge loops
Python
def merge_lists(list_a, list_b):
    merged = []
    for item in list_a:
        merged.append(item)
    for item in list_b:
        merged.append(item)
    return merged


if __name__ == "__main__":
    fruits = ["apple", "banana"]
    vegetables = ["carrot", "spinach"]
    result = merge_lists(fruits, vegetables)
  …
14 0 Open
Lists & loops easy

How to Merge Two Sorted Lists in Python

Merge two sorted lists into one sorted list using a two-pointer loop, then extend with remaining elements.

sorting merge two-pointers
Python
def merge_sorted_lists(list1, list2):
    merged = []
    i = j = 0
    
    while i < len(list1) and j < len(list2):
        if list1[i] <= list2[j]:
            merged.append(list1[i])
            i += 1
        else:
            merged.append(list2[j])
            j += 1
    
    merged.extend(list1[i:])
    merged…
14 0 Open
Lists & loops easy

How to Normalize a List of Numbers in Python

This Python function normalizes a list of numeric values to the range [0, 1] using min-max scaling, returning a new list and leaving the original unchanged.

lists loops normalization
Python
def normalize(data):
    """
    Normalize a list of numeric values to the range [0, 1].
    Returns a new list, leaving the original unchanged.
    """
    if not data:
        return []
    
    min_val = min(data)
    max_val = max(data)
    
    # Handle the edge case where all values are identical
    if min_val …
17 0 Open
Lists & loops easy

How to Normalize a List of Numbers to the 0-1 Range in Python

Scale a list of numbers so the minimum becomes 0 and the maximum becomes 1 using min-max normalization.

normalization lists data-science
Python
def min_max_normalize(values):
    """Normalize a list of numbers to the [0, 1] range."""
    if not values:
        return []
    min_val = min(values)
    max_val = max(values)
    if min_val == max_val:
        return [0.0] * len(values)
    return [(x - min_val) / (max_val - min_val) for x in values]


if __name__…
12 0 Open
Lists & loops easy

How to Pad a List to Length n in Python with a Fill Value

Create a reusable function that pads a Python list to a specified length n by appending a fill value, or truncates it when the list is already longer than n.

lists padding slicing
Python
def pad_list(lst, n, fill_value=None):
    """
    Pad a list to length n using fill_value for missing elements.
    If the list is longer than n, it is truncated to length n.
    """
    if n <= len(lst):
        return lst[:n]
    return lst + [fill_value] * (n - len(lst))


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

How to Parse Delimited Data into a Python List

Splits a pipe-delimited string, strips whitespace, filters empty items, and returns a clean list with a loop.

strings lists loops
Python
def parse_data(raw_data):
    """Parse a pipe-delimited string into a list of cleaned items."""
    items = raw_data.split("|")
    parsed = []
    for item in items:
        cleaned = item.strip()
        if cleaned:
            parsed.append(cleaned)
    return parsed


if __name__ == "__main__":
    data = "  apple…
15 0 Open
Lists & loops easy

How to Process Text Lines with Lists and Loops in Python

This code processes a list of text lines by stripping whitespace, converting to uppercase, and reporting character counts per line and totals.

lists loops text-processing
Python
def process_text(lines):
    """Convert a list of text lines to uppercase and report line statistics."""
    processed = []
    total_chars = 0
    
    for index, line in enumerate(lines, start=1):
        cleaned = line.strip().upper()
        processed.append(cleaned)
        total_chars += len(cleaned)
        pri…
12 0 Open
Lists & loops easy

How to Process Text with Lists and Loops in Python

A beginner-friendly text processor that splits a sentence into words, filters by length, counts vowels, and reports results using lists and loops.

lists loops strings
Python
text = "Python makes text processing easy and fun"

words = text.lower().split()

print("Words in the sentence:")
for index, word in enumerate(words, start=1):
    print(f"{index}. {word}")

filtered_words = [word for word in words if len(word) > 3]

print(f"\nWords longer than 3 characters: {filtered_words}")

letter…
14 0 Open
Lists & loops easy

How to Process Text with Lists and Loops in Python

Iterate over a list of text lines to count words, show uppercase versions, and report character counts per line.

lists loops enumerate
Python
# text_processor.py

def process_text(lines):
    """Count words, show uppercase, and count characters per line."""
    total_words = 0
    print("Line-by-line analysis:")
    for i, line in enumerate(lines, start=1):
        words = line.split()
        total_words += len(words)
        print(f"  Line {i}: {len(words…
17 0 Open
Lists & loops easy

How to Reverse a List in Place Without Using reverse() in Python

A two-pointer while loop swaps elements from both ends toward the center to reverse a list in place without creating a copy.

lists in-place two-pointer
Python
def reverse_list_in_place(lst):
    left = 0
    right = len(lst) - 1
    while left < right:
        lst[left], lst[right] = lst[right], lst[left]
        left += 1
        right -= 1


if __name__ == "__main__":
    my_list = [1, 2, 3, 4, 5]
    print("Original:", my_list)
    reverse_list_in_place(my_list)
    prin…
14 0 Open
Lists & loops easy

How to Shuffle a List in Python

Shuffle a Python list in place or return a new shuffled copy using the random module.

random shuffle lists
Python
import random

def shuffle_list(items):
    shuffled = items[:]
    random.shuffle(shuffled)
    return shuffled

if __name__ == "__main__":
    original = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    result = shuffle_list(original)
    print(f"Original: {original}")
    print(f"Shuffled: {result}")
14 0 Open
Lists & loops easy

How to Sort a List in Python in Ascending and Descending Order

This code demonstrates three ways to sort a list in Python: returning a new sorted list with sorted(), reversing the sort order, and sorting a list in place with the list.sort() method.

sort sorted lists
Python
def get_sorted_data(numbers):
    """Return a new list sorted in ascending order."""
    return sorted(numbers)


def reverse_sort(data):
    """Return a new list sorted in descending order."""
    return sorted(data, reverse=True)


def sort_in_place(data):
    """Sort the given list in place (modifies original)."""
…
12 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 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 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 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

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.