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 Local Minima (Valleys) in a Numeric List in Python
This code finds indices of all local minima (valleys) in a numeric list, including edge cases, using a simple loop that compares each element with its neighbors.
def find_local_minima(numbers):
"""Find indices of local minima (valleys) in a numeric list.
A value is a local minimum if it's less than or equal to its neighbors.
Edge elements are considered minima if they're less than or equal to their single neighbor.
"""
if not numbers:
return []…
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]
…
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 Compute a Moving Average in Python
This code computes the moving average over a numeric list using an efficient sliding window sum, avoiding recomputation of each window.
def moving_average(data, window_size):
"""
Compute the moving average over a numeric list.
Args:
data: List of numeric values
window_size: Size of the sliding window (positive integer)
Returns:
List of moving averages, each representing the mean of a window
"""
…
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 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 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 …
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.