Lists & loops
Iterate, transform, and combine sequences with readable loop patterns.
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 Maximum Value in a List of Numbers in Python
Iterate through a list with a for loop to manually find and return the maximum numeric value.
def find_max(numbers):
"""Return the maximum value in a list of 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, 15, 9, 11]
…
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…
How to Build a Running Maximum List in Python
Compute a list where each element is the maximum of all numbers seen so far from an input list.
def running_maximum(numbers):
result = []
current_max = float('-inf')
for num in numbers:
if num > current_max:
current_max = num
result.append(current_max)
return result
if __name__ == "__main__":
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
max_list = running_maximum(number…
How to Calculate the Sum of List Elements in Python
Iterates over a list with a for loop, accumulates each number into a total variable, and returns the sum of all elements.
def sum_list_elements(numbers):
"""Return the sum of all elements in a list."""
total = 0
for num in numbers:
total += num
return total
if __name__ == "__main__":
sample_list = [1, 2, 3, 4, 5]
result = sum_list_elements(sample_list)
print(f"The sum of {sample_list} is {result}")
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 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 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 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 …
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.