Lists & loops
Iterate, transform, and combine sequences with readable loop patterns.
How to Filter Empty Strings in Python
Remove empty and whitespace-only strings from a list using a list comprehension with the strip() method.
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…
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.
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)}")
How to Parse a Comma String into a List of Integers in Python
Converts a comma-separated string into a list of integers, handling spaces and empty inputs.
def parse_csv_to_ints(text: str) -> list[int]:
"""Parse a comma-separated string into a list of integers."""
if not text.strip():
return []
return [int(part.strip()) for part in text.split(",") if part.strip()]
if __name__ == "__main__":
sample = "10, 20, 30, 40, 50"
result = parse_csv_to_…
How to Process Text with Lists and Loops in Python
A beginner-friendly text processor that splits a sentence into words, filters by length, counts vowels, and reports results using lists and loops.
text = "Python makes text processing easy and fun"
words = text.lower().split()
print("Words in the sentence:")
for index, word in enumerate(words, start=1):
print(f"{index}. {word}")
filtered_words = [word for word in words if len(word) > 3]
print(f"\nWords longer than 3 characters: {filtered_words}")
letter…
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.
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…
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.
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}")
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.