Reference library

Lists & loops

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

11 matches
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 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 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 Safely Convert a List of Strings to Integers in Python

Convert a list of strings to integers while skipping invalid entries and collecting the failed values for inspection.

list conversion int conversion error handling
Python
def safe_to_int(values):
    """Safely convert a list of strings to integers, skipping invalid entries."""
    result = []
    errors = []
    for value in values:
        try:
            result.append(int(value))
        except (ValueError, TypeError):
            errors.append(value)
    return result, errors


if …
13 0 Open
Lists & loops easy

How to Truncate a List to Max Length in Python (Keep Head)

This code returns a new list containing only the first max_length items from the original list, using Python's slice syntax.

list slicing truncate
Python
from typing import List

def truncate_head(lst: List[object], max_length: int) -> List[object]:
    """Return a new list with at most max_length items from the head."""
    if max_length < 0:
        raise ValueError("max_length must be non-negative")
    return lst[:max_length]

if __name__ == "__main__":
    # Examp…
14 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
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 unzip a list of pairs into two lists in Python

Split a list of (a, b) tuples into two separate lists by iterating with a for loop and appending each element to its own output list.

lists tuples loops
Python
def unzip(pairs):
    """Split a list of (a, b) pairs into two separate lists."""
    if not pairs:
        return [], []
    
    firsts = []
    seconds = []
    for a, b in pairs:
        firsts.append(a)
        seconds.append(b)
    
    return firsts, seconds


if __name__ == "__main__":
    pairs = [(1, 'a'), (…
14 0 Open
Lists & loops easy

Pairwise Adjacent Differences in a Python List

Computes the absolute differences between each pair of adjacent elements in a list using a concise list comprehension.

list-comprehension differences absolute-value
Python
def adjacent_differences(nums):
    """Return list of absolute differences between adjacent elements."""
    return [abs(nums[i] - nums[i + 1]) for i in range(len(nums) - 1)]


if __name__ == "__main__":
    sample = [3, 7, 2, 9, 5]
    diffs = adjacent_differences(sample)
    print("Original list:", sample)
    print…
14 0 Open
Lists & loops easy

Separate Evens and Odds into Two Lists in Python

Split a list of numbers into two lists containing even and odd numbers using a simple loop and the modulo operator.

lists loops modulo
Python
def separate_evens_odds(numbers):
    evens = []
    odds = []
    for num in numbers:
        if num % 2 == 0:
            evens.append(num)
        else:
            odds.append(num)
    return evens, odds

if __name__ == "__main__":
    nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    evens, odds = separate_evens_odds(nu…
13 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.