Reference library

Lists & loops

Iterate, transform, and combine sequences with readable loop patterns.

21 matches
Lists & loops easy

Check if List is Sorted Ascending in Python

Verify that a list is sorted in ascending order using the all() function and a generator expression.

lists sorted all
Python
def is_sorted_ascending(lst):
    return all(lst[i] <= lst[i + 1] for i in range(len(lst) - 1))

if __name__ == "__main__":
    test_lists = [
        [1, 2, 3, 4, 5],
        [1, 3, 2, 4, 5],
        [5, 4, 3, 2, 1],
        [1, 1, 2, 2, 3],
        [10],
        []
    ]
    for lst in test_lists:
        print(f"{l…
19 0 Open
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 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

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

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

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

Browse by section

Each section groups closely related Python snippets.

Lists & loops — Python code examples

What you will find here

This page collects lists & loops snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

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.