Reference library

Lists & loops

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

7 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 Build a Frequency Map from a List in Python

This code builds a dictionary that maps each unique element in a list to its count using the Counter class from the collections module.

counter frequency dictionary
Python
from collections import Counter

def build_frequency_map(values):
    """Return a dictionary mapping each unique value to its frequency."""
    return dict(Counter(values))

if __name__ == "__main__":
    data = ["apple", "banana", "apple", "cherry", "banana", "apple"]
    freq_map = build_frequency_map(data)
    prin…
13 0 Open
Lists & loops easy

How to Calculate a Cumulative Sum in Python

Build a new list where each element equals the running total of all numbers up to that index in the original list.

lists cumulative-sum loops
Python
numbers = [1, 2, 3, 4, 5]
cumulative_sum = []
running_total = 0

for num in numbers:
    running_total += num
    cumulative_sum.append(running_total)

print(cumulative_sum)
12 0 Open
Lists & loops easy

How to Find the Mode in a Python List

Find the most frequent value (mode) in a Python list using the collections.Counter class, handling empty lists and ties.

mode counter frequency
Python
from collections import Counter

def find_mode(numbers):
    if not numbers:
        return None
    counts = Counter(numbers)
    max_count = max(counts.values())
    modes = [num for num, count in counts.items() if count == max_count]
    return modes[0] if len(modes) == 1 else modes

if __name__ == "__main__":
    …
14 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 Partition a List Around a Pivot in Python

This code splits a list into three parts—elements less than, equal to, and greater than a pivot—then concatenates them to produce a partitioned list while preserving the original order within each group.

partition list pivot
Python
def partition_list(lst, pivot):
    less = []
    equal = []
    greater = []
    for item in lst:
        if item < pivot:
            less.append(item)
        elif item == pivot:
            equal.append(item)
        else:
            greater.append(item)
    return less + equal + greater

if __name__ == "__main__…
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.

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.