Lists & loops
Iterate, transform, and combine sequences with readable loop patterns.
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.
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…
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.
fruits = ["apple", "banana", "cherry", "date"]
for index, fruit in enumerate(fruits, start=5):
print(f"{index}: {fruit}")
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.
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…
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.
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:
…
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.
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}")
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.
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 …
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 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 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 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 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 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 Sort a List of Dictionaries by a Key in Python
Sort a list of dictionaries by a specified key field, optionally in descending order, using Python's built-in sorted() function.
def sort_dicts_by_key(data, key, reverse=False):
return sorted(data, key=lambda item: item.get(key), reverse=reverse)
if __name__ == "__main__":
people = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35},
]
sorted_by_age = sort_dicts_b…
How to Sort a List of Tuples by the Second Element in Python
Sorts a list of tuples by the second element using the sorted() function with a lambda key, preserving the original list.
def sort_tuples_by_second(tuples_list):
"""Sort a list of tuples by the second element."""
return sorted(tuples_list, key=lambda x: x[1])
if __name__ == "__main__":
data = [(1, 5), (3, 2), (2, 8), (4, 1)]
sorted_data = sort_tuples_by_second(data)
print("Original list:", data)
print("Sorted by…
How to Split a List at the First Occurrence of a Value in Python
This function splits a list into two parts at the first occurrence of a given value, returning the left and right portions.
def split_at_first(lst, value):
try:
idx = lst.index(value)
return lst[:idx], lst[idx:]
except ValueError:
return lst, []
if __name__ == "__main__":
sample = [1, 2, 3, 4, 3, 5]
value = 3
left, right = split_at_first(sample, value)
print("Left:", left)
print("Right:"…
How to Validate List Data in Python
A beginner-friendly validation helper that checks if data is a list, enforces minimum length, and optionally verifies item types with clear error messages.
def validate_data(data, expected_types=None, min_length=1):
"""Validate that data is a non-empty list and optionally check item types."""
if not isinstance(data, list):
return False, f"Expected a list, got {type(data).__name__}"
if len(data) < min_length:
return False, f"List must have…
How to Zip Two Lists into Pairs in Python
Combine two lists element-wise into a list of tuples using Python's built-in zip() function.
def zip_lists_into_pairs(list1, list2):
pairs = list(zip(list1, list2))
return pairs
if __name__ == "__main__":
fruits = ["apple", "banana", "cherry"]
quantities = [3, 5, 2]
result = zip_lists_into_pairs(fruits, quantities)
print(result)
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…
How to summarize and transform lists in Python
Compute count, sum, min, max, and average for a list and multiply each element by a factor using simple loops and built-in functions.
def summarize(data):
"""Return a summary of a list: count, sum, min, max, average."""
count = len(data)
total = sum(data)
minimum = min(data)
maximum = max(data)
average = total / count if count else 0
return count, total, minimum, maximum, average
def multiply_elements(data, factor=2):
…
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}")
Symmetric difference between two lists in Python
Find elements present in exactly one of two lists, preserving original order, with a simple Python function.
def symmetric_difference(list1, list2):
"""
Return the symmetric difference of two lists.
Elements present in exactly one of the lists, preserving order.
"""
set1 = set(list1)
set2 = set(list2)
# Elements in list1 but not in list2
diff1 = [x for x in list1 if x not in set2]
# E…
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.