Reference library

Lists & loops

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

8 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

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 Percentile Value from Sorted List in Python

Compute any percentile value from a sorted list using linear interpolation between ranks.

percentile statistics interpolation
Python
def percentile(sorted_data, percentile_value):
    """Return the value below which `percentile_value`% of data falls."""
    if not sorted_data:
        raise ValueError("Cannot compute percentile of empty list")
    if not 0 <= percentile_value <= 100:
        raise ValueError("Percentile must be between 0 and 100")
…
16 0 Open
Lists & loops easy

How to Find the Median of a List in Python

Compute the median of an unsorted numeric list using the statistics module in Python.

median statistics lists
Python
import statistics

def median_of_list(numbers):
    return statistics.median(numbers)

if __name__ == "__main__":
    sample = [7, 3, 1, 4, 9, 2, 8]
    print(median_of_list(sample))
12 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 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 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

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.