Reference library

Lists & loops

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

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

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.