Lists & loops
Iterate, transform, and combine sequences with readable loop patterns.
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 Process Text Lines with Lists and Loops in Python
This code processes a list of text lines by stripping whitespace, converting to uppercase, and reporting character counts per line and totals.
def process_text(lines):
"""Convert a list of text lines to uppercase and report line statistics."""
processed = []
total_chars = 0
for index, line in enumerate(lines, start=1):
cleaned = line.strip().upper()
processed.append(cleaned)
total_chars += len(cleaned)
pri…
How to Process Text with Lists and Loops in Python
A beginner-friendly text processor that splits a sentence into words, filters by length, counts vowels, and reports results using lists and loops.
text = "Python makes text processing easy and fun"
words = text.lower().split()
print("Words in the sentence:")
for index, word in enumerate(words, start=1):
print(f"{index}. {word}")
filtered_words = [word for word in words if len(word) > 3]
print(f"\nWords longer than 3 characters: {filtered_words}")
letter…
How to Process Text with Lists and Loops in Python
Iterate over a list of text lines to count words, show uppercase versions, and report character counts per line.
# text_processor.py
def process_text(lines):
"""Count words, show uppercase, and count characters per line."""
total_words = 0
print("Line-by-line analysis:")
for i, line in enumerate(lines, start=1):
words = line.split()
total_words += len(words)
print(f" Line {i}: {len(words…
How to Reverse a List in Place Without Using reverse() in Python
A two-pointer while loop swaps elements from both ends toward the center to reverse a list in place without creating a copy.
def reverse_list_in_place(lst):
left = 0
right = len(lst) - 1
while left < right:
lst[left], lst[right] = lst[right], lst[left]
left += 1
right -= 1
if __name__ == "__main__":
my_list = [1, 2, 3, 4, 5]
print("Original:", my_list)
reverse_list_in_place(my_list)
prin…
How to Shuffle a List in Python
Shuffle a Python list in place or return a new shuffled copy using the random module.
import random
def shuffle_list(items):
shuffled = items[:]
random.shuffle(shuffled)
return shuffled
if __name__ == "__main__":
original = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = shuffle_list(original)
print(f"Original: {original}")
print(f"Shuffled: {result}")
How to Sort a List in Python in Ascending and Descending Order
This code demonstrates three ways to sort a list in Python: returning a new sorted list with sorted(), reversing the sort order, and sorting a list in place with the list.sort() method.
def get_sorted_data(numbers):
"""Return a new list sorted in ascending order."""
return sorted(numbers)
def reverse_sort(data):
"""Return a new list sorted in descending order."""
return sorted(data, reverse=True)
def sort_in_place(data):
"""Sort the given list in place (modifies original)."""
…
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 into Chunks in Python
Split a list into fixed-size sublists using a simple list comprehension with slicing.
def chunk_list(lst, size):
"""Split a list into sublists of given size."""
return [lst[i:i + size] for i in range(0, len(lst), size)]
if __name__ == "__main__":
sample = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(chunk_list(sample, 3))
How to Standardize a List with Z-Score Normalization in Python
This code computes the z-score for each number in a list, standardizing the data to have zero mean and unit variance using the statistics module.
import statistics
def z_score_normalize(values):
"""Standardize a list of numbers using z-score normalization."""
if not values or len(values) < 2:
raise ValueError("Need at least 2 values for meaningful z-score normalization")
mean = statistics.mean(values)
std_dev = statistics.stdev(val…
How to Summarize a List of Numbers in Python
Loop over a list of numbers to compute total, count, average, min, and max, then return them in a dictionary.
def summarize_numbers(numbers):
"""Return a dict with basic stats for a list of numbers."""
total = 0
count = 0
smallest = numbers[0]
largest = numbers[0]
for num in numbers:
total += num
count += 1
if num < smallest:
smallest = num
if num > largest:…
How to Transpose a Matrix in Python (List of Lists)
Swap rows and columns of a 2D list using nested loops to produce a transposed matrix.
def transpose(matrix):
# Number of rows and columns in the original matrix
rows = len(matrix)
cols = len(matrix[0]) if rows > 0 else 0
# Create a new matrix with dimensions swapped
result = []
for j in range(cols):
new_row = []
for i in range(rows):
new_row.appe…
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 Validate Text Against Forbidden Words in Python
Checks whether a given text contains any forbidden words and returns a tuple with validity and offending words.
def validate_text(text, forbidden_words):
"""
Checks that text does not contain any forbidden words.
Returns (is_valid, offending_words) tuple.
"""
words = text.lower().split()
found = [word for word in words if word in forbidden_words]
return len(found) == 0, found
if __name__ == "__main…
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 check list items by type and emptiness in Python
Loop through a list with enumerate(), classify each item as empty, number, or text, and print a formatted status for each element.
def check_data(data):
"""Check each item in a list and print whether it's valid."""
for i, item in enumerate(data):
if item is None or item == "":
status = "empty"
elif isinstance(item, (int, float)):
status = "number"
else:
status = "text"
pr…
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…
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.