Lists & loops
Iterate, transform, and combine sequences with readable loop patterns.
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.
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:
…
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.
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__…
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 Find Local Maxima in a Python List
Return the indices of all local maxima in a numeric list, where a peak is an element greater than both its immediate neighbors.
def find_peaks(numbers):
"""
Return the indices of local maxima in a numeric list.
A local maximum is an element greater than both its neighbors.
"""
if len(numbers) < 3:
return []
peaks = []
for i in range(1, len(numbers) - 1):
if numbers[i] > numbers[i - 1] and number…
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.
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…
How to Find the Median of a List in Python
Compute the median of an unsorted numeric list using the statistics module in Python.
import statistics
def median_of_list(numbers):
return statistics.median(numbers)
if __name__ == "__main__":
sample = [7, 3, 1, 4, 9, 2, 8]
print(median_of_list(sample))
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.
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__":
…
How to Find the Third Smallest Element in a Python List
Find the third smallest distinct value in a Python list by sorting unique elements and returning the third index.
def find_third_smallest(numbers):
if len(numbers) < 3:
return None
unique_sorted = sorted(set(numbers))
if len(unique_sorted) < 3:
return None
return unique_sorted[2]
if __name__ == "__main__":
sample = [5, 2, 8, 2, 9, 1, 7, 3]
result = find_third_smallest(sampl…
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.
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…
How to Flatten a Deeply Nested List in Python Recursively
A recursive function that flattens arbitrarily deep nested lists into a single flat list using isinstance checks.
def flatten(nested_list):
if not nested_list:
return []
if isinstance(nested_list[0], list):
return flatten(nested_list[0]) + flatten(nested_list[1:])
return [nested_list[0]] + flatten(nested_list[1:])
if __name__ == "__main__":
data = [1, [2, [3, [4, [5]]]], [6, [7, [8, [9]]]], 10]
…
How to Get the Union of Two Lists Without Duplicates in Python
Merge two lists and remove duplicate values using a set, then convert back to a list.
def union_without_duplicates(list1, list2):
return list(set(list1 + list2))
if __name__ == "__main__":
list_a = [1, 2, 3, 4]
list_b = [3, 4, 5, 6]
result = union_without_duplicates(list_a, list_b)
print(f"Union of {list_a} and {list_b}: {result}")
How to Group Consecutive Equal Elements in Python
Group consecutive equal elements in a list into sublists using itertools.groupby.
from itertools import groupby
def group_consecutive(lst):
"""Group consecutive equal elements into sublists."""
return [list(group) for _, group in groupby(lst)]
if __name__ == "__main__":
input_list = [1, 1, 2, 2, 2, 3, 1, 1, 4, 4, 4, 4]
result = group_consecutive(input_list)
print("Input:", inp…
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.
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))
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 Merge Two Lists in Python
Merge two Python lists into a single combined list by appending each element with a simple loop, achieving the same result as the + operator.
def merge_lists(list_a, list_b):
merged = []
for item in list_a:
merged.append(item)
for item in list_b:
merged.append(item)
return merged
if __name__ == "__main__":
fruits = ["apple", "banana"]
vegetables = ["carrot", "spinach"]
result = merge_lists(fruits, vegetables)
…
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.
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…
How to Normalize a List of Numbers in Python
This Python function normalizes a list of numeric values to the range [0, 1] using min-max scaling, returning a new list and leaving the original unchanged.
def normalize(data):
"""
Normalize a list of numeric values to the range [0, 1].
Returns a new list, leaving the original unchanged.
"""
if not data:
return []
min_val = min(data)
max_val = max(data)
# Handle the edge case where all values are identical
if min_val …
How to Normalize a List of Numbers to the 0-1 Range in Python
Scale a list of numbers so the minimum becomes 0 and the maximum becomes 1 using min-max normalization.
def min_max_normalize(values):
"""Normalize a list of numbers to the [0, 1] range."""
if not values:
return []
min_val = min(values)
max_val = max(values)
if min_val == max_val:
return [0.0] * len(values)
return [(x - min_val) / (max_val - min_val) for x in values]
if __name__…
How to Pad a List to Length n in Python with a Fill Value
Create a reusable function that pads a Python list to a specified length n by appending a fill value, or truncates it when the list is already longer than n.
def pad_list(lst, n, fill_value=None):
"""
Pad a list to length n using fill_value for missing elements.
If the list is longer than n, it is truncated to length n.
"""
if n <= len(lst):
return lst[:n]
return lst + [fill_value] * (n - len(lst))
if __name__ == "__main__":
# Examples…
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 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_…
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.