Reference library

Lists & loops

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

6 matches
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 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 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
Lists & loops easy

How to Split a List into Chunks in Python

Split a list into fixed-size sublists using a simple list comprehension with slicing.

list slicing chunking
Python
def chunk_list(lst, size):
    """Split a list into sublists of given size."""
    return [lst[i:i + size] for i in range(0, len(lst), size)]


if __name__ == "__main__":
    sample = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    print(chunk_list(sample, 3))
13 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

Replace Negative Values in a List with Python

This code defines a function that replaces every negative number in a list with a replacement value, defaulting to zero, using a list comprehension.

list-comprehension data-cleaning list-transformation
Python
def replace_if_negative(values, replacement=0):
    return [replacement if value < 0 else value for value in values]

if __name__ == "__main__":
    numbers = [5, -3, 8, -1, 0, -7, 2]
    result = replace_if_negative(numbers)
    print(f"Original: {numbers}")
    print(f"Replaced: {result}")
14 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.