Reference library

Lists & loops

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

58 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

Convert a List of Integers to a Comma-Separated String in Python

Convert a list of integers into a single comma-separated string using a generator expression and str.join.

join list comma
Python
def ints_to_comma_string(numbers):
    return ",".join(str(num) for num in numbers)

if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5]
    result = ints_to_comma_string(numbers)
    print(result)
15 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 Maximum Value in a List of Numbers in Python

Iterate through a list with a for loop to manually find and return the maximum numeric value.

max list loop
Python
def find_max(numbers):
    """Return the maximum value in a list of 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, 15, 9, 11]
…
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

Find Most Active Contributors in a Repository with Python

Filter recent commits by date and count the most active contributors using Counter and datetime.

collections datetime counter
Python
from collections import Counter
from datetime import datetime, timedelta

# Simulated commit data
commits = [
    {"author": "Alice", "timestamp": datetime.now() - timedelta(days=1)},
    {"author": "Bob", "timestamp": datetime.now() - timedelta(days=2)},
    {"author": "Alice", "timestamp": datetime.now() - timedelta…
45 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 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 Build a Running Maximum List in Python

Compute a list where each element is the maximum of all numbers seen so far from an input list.

running-max iteration lists
Python
def running_maximum(numbers):
    result = []
    current_max = float('-inf')
    for num in numbers:
        if num > current_max:
            current_max = num
        result.append(current_max)
    return result

if __name__ == "__main__":
    numbers = [3, 1, 4, 1, 5, 9, 2, 6]
    max_list = running_maximum(number…
15 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 Calculate the Sum of List Elements in Python

Iterates over a list with a for loop, accumulates each number into a total variable, and returns the sum of all elements.

sum list loop
Python
def sum_list_elements(numbers):
    """Return the sum of all elements in a list."""
    total = 0
    for num in numbers:
        total += num
    return total

if __name__ == "__main__":
    sample_list = [1, 2, 3, 4, 5]
    result = sum_list_elements(sample_list)
    print(f"The sum of {sample_list} is {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 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")
…
15 0 Open
Lists & loops easy

How to Compute a Moving Average in Python

This code computes the moving average over a numeric list using an efficient sliding window sum, avoiding recomputation of each window.

moving-average sliding-window lists
Python
def moving_average(data, window_size):
    """
    Compute the moving average over a numeric list.
    
    Args:
        data: List of numeric values
        window_size: Size of the sliding window (positive integer)
    
    Returns:
        List of moving averages, each representing the mean of a window
    """
   …
14 0 Open
Lists & loops easy

How to Convert Data Types in Python Lists

Convert a mixed list of values to integers, floats, or strings based on their content, with graceful fallback for unparseable strings.

type-conversion loops lists
Python
def convert_data(data):
    """Convert a mixed list of values to strings, ints, and floats."""
    result = []
    for item in data:
        if isinstance(item, (int, float)):
            result.append(str(item))
        elif isinstance(item, str):
            try:
                if '.' in item:
                    r…
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 Cycle Through a List Infinitely with itertools

This code uses itertools.cycle to create an infinite iterator over a list and returns the first n items from that cycle.

itertools cycle infinite iteration
Python
from itertools import cycle

def demonstrate_cycle(items, cycles=3):
    """
    Cycle through a list infinitely using itertools.cycle.
    Returns the first n items from the infinite cycle.
    """
    cycled = cycle(items)
    result = [next(cycled) for _ in range(len(items) * cycles)]
    return result

if __name__…
14 0 Open
Lists & loops easy

How to Filter Empty Strings in Python

Remove empty and whitespace-only strings from a list using a list comprehension with the strip() method.

filtering strings list-comprehension
Python
def filter_empty_strings(strings):
    """
    Filter out empty strings (including whitespace-only strings)
    from a list of strings.
    """
    return [s for s in strings if s.strip()]


if __name__ == "__main__":
    sample_list = ["hello", "", "world", "   ", "python", " ", "!"]
    filtered = filter_empty_strin…
12 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 Filter None Values from a Mixed List in Python

Filter None values from a mixed Python list using a list comprehension with the `is not None` condition.

filter list-comprehension none
Python
mixed_list = [1, None, "hello", None, 3.14, None, [1, 2], None]

filtered_list = [item for item in mixed_list if item is not None]

print(f"Original list: {mixed_list}")
print(f"Filtered list: {filtered_list}")
print(f"Original length: {len(mixed_list)}, Filtered length: {len(filtered_list)}")
15 0 Open
Lists & loops easy

How to Filter a List in Python with a Loop

Filter a list of numbers by a threshold using a for loop and append results to a new list, then print the filtered values and count.

filter for-loop lists
Python
ages = [34, 12, 45, 8, 67, 21, 18, 55, 3]
threshold = 18

adults = []
for age in ages:
    if age >= threshold:
        adults.append(age)

print("All ages:", ages)
print("Adults (18+):", adults)
print("Count of adults:", len(adults))
10 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 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 Flatten One Level of a Nested List in Python

Flattens exactly one level of a nested list by extending the output with each inner list and appending non-list items.

flatten nested list list comprehension
Python
def flatten_one_level(nested_list):
    """Flatten one level of a nested list."""
    flattened = []
    for item in nested_list:
        if isinstance(item, list):
            flattened.extend(item)
        else:
            flattened.append(item)
    return flattened

if __name__ == "__main__":
    # Example with mi…
15 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.