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…
Compare Two Lists in Python: Common, Only in First, Only in Second
A beginner-friendly helper that loops over two lists and returns items common to both, items only in the first list, and items only in the second list.
def compare_lists(list1, list2):
common = []
only_in_first = []
only_in_second = []
for item in list1:
if item in list2:
common.append(item)
else:
only_in_first.append(item)
for item in list2:
if item not in list1:
only_in_second…
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}")
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 Duplicate Elements in a Python List
Identifies and returns duplicate elements from a Python list using sets for efficient membership tests.
def find_duplicates(lst):
seen = set()
duplicates = set()
for item in lst:
if item in seen:
duplicates.add(item)
else:
seen.add(item)
return list(duplicates)
if __name__ == "__main__":
sample = [1, 2, 3, 2, 4, 1, 5, 3]
print(find_duplicates(sample))
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…
Format Lists of Tuples into Numbered Lines in Python
This code loops through a list of (name, grade) tuples and formats each into a numbered line using enumerate and f-strings.
def format_students(students):
formatted = []
for i, student in enumerate(students, start=1):
name, grade = student
formatted.append(f"{i}. {name}: {grade}")
return "\n".join(formatted)
if __name__ == "__main__":
students = [
("Alice", 92),
("Bob", 85),
("Charl…
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 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 Build a Text Processor with Lists and Loops in Python
A beginner-friendly Python script that analyzes text by counting sentences, words, and word lengths using lists and for loops, then prints the results.
def process_text(text):
"""Simple text processor for beginners using lists and loops."""
sentences = text.replace('!', '.').replace('?', '.').split('.')
words = text.split()
word_counts = []
for sentence in sentences:
sentence_word_count = len(sentence.split())
word_counts.appe…
How to Calculate a Cumulative Sum in Python
Build a new list where each element equals the running total of all numbers up to that index in the original list.
numbers = [1, 2, 3, 4, 5]
cumulative_sum = []
running_total = 0
for num in numbers:
running_total += num
cumulative_sum.append(running_total)
print(cumulative_sum)
How to Compute Percentile Value from Sorted List in Python
Compute any percentile value from a sorted list using linear interpolation between ranks.
def percentile(sorted_data, percentile_value):
"""Return the value below which `percentile_value`% of data falls."""
if not sorted_data:
raise ValueError("Cannot compute percentile of empty list")
if not 0 <= percentile_value <= 100:
raise ValueError("Percentile must be between 0 and 100")
…
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 Convert Data Types in Python Lists
Convert a mixed list of values to integers, floats, or strings based on their content, with graceful fallback for unparseable strings.
def convert_data(data):
"""Convert a mixed list of values to strings, ints, and floats."""
result = []
for item in data:
if isinstance(item, (int, float)):
result.append(str(item))
elif isinstance(item, str):
try:
if '.' in item:
r…
How to Count Occurrences of a Value in a Python List
Counts how many times a specific value appears in a list using a simple loop and a counter variable.
def count_occurrences(data, target):
count = 0
for item in data:
if item == target:
count += 1
return count
if __name__ == "__main__":
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
target_value = 5
result = count_occurrences(numbers, target_value)
print(f"The value {targ…
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 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 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 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}")
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.