Lists & loops
Iterate, transform, and combine sequences with readable loop patterns.
Extract Data by Type from a List in Python: Numbers and Strings
Loop through a mixed list to filter out numeric and string values into separate lists.
def extract_numbers(items):
"""Extract all numeric values from a mixed list."""
numbers = []
for item in items:
if isinstance(item, (int, float)) and not isinstance(item, bool):
numbers.append(item)
return numbers
def extract_strings(items):
"""Extract all string values from a…
Find Most Active Contributors in a Repository with Python
Filter recent commits by date and count the most active contributors using Counter and datetime.
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…
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 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.
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 …
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 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.
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))
How to Loop Through Lists in Python for Beginners
Transform, filter, sum, and find the maximum in a Python list using basic for loops and conditionals.
def transform_data(numbers):
"""Basic transformation examples using lists and loops."""
doubled = []
for n in numbers:
doubled.append(n * 2)
return doubled
def filter_even(numbers):
"""Keep only even numbers using a loop and condition."""
evens = []
for n in numbers:
if n …
How to Parse Bullet Points in Python
Extract bullet point items from raw text by splitting lines and filtering those that start with '- ' or '* '.
def parse_bullet_points(text):
"""Extract bullet point items from raw text."""
lines = text.splitlines()
items = []
for line in lines:
stripped = line.strip()
if stripped.startswith("- ") or stripped.startswith("* "):
item = stripped[2:]
if item:
…
How to Parse Delimited Data into a Python List
Splits a pipe-delimited string, strips whitespace, filters empty items, and returns a clean list with a loop.
def parse_data(raw_data):
"""Parse a pipe-delimited string into a list of cleaned items."""
items = raw_data.split("|")
parsed = []
for item in items:
cleaned = item.strip()
if cleaned:
parsed.append(cleaned)
return parsed
if __name__ == "__main__":
data = " apple…
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…
How to split a list by condition in Python
Splits a list into two lists based on a condition function, returning matched and unmatched items.
def split_by_condition(items, condition):
"""
Split a list into two lists based on a condition.
The first list contains items where condition(item) is True,
the second list contains the rest.
"""
matched = []
unmatched = []
for item in items:
if condition(item):
matc…
Intersection of Two Lists Preserving Order in Python
This code returns the common elements between two lists while preserving the order they appear in the first list, filtering out duplicates.
def intersection_preserving_order(list1, list2):
"""
Return the intersection of two lists while preserving the order
of elements as they appear in list1.
"""
set2 = set(list2)
result = []
seen = set()
for item in list1:
if item in set2 and item not in seen:
resu…
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.