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 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 Safely Convert a List of Strings to Integers in Python
Convert a list of strings to integers while skipping invalid entries and collecting the failed values for inspection.
def safe_to_int(values):
"""Safely convert a list of strings to integers, skipping invalid entries."""
result = []
errors = []
for value in values:
try:
result.append(int(value))
except (ValueError, TypeError):
errors.append(value)
return result, errors
if …
Round Robin Merge Multiple Lists in Python
Merge multiple lists by taking one element from each in turn, stopping when all lists are exhausted.
from itertools import cycle
def round_robin_merge(*lists):
"""Merge multiple lists by taking one element from each in turn."""
result = []
max_len = max(len(lst) for lst in lists)
for i in range(max_len):
for lst in lists:
if i < len(lst):
result.append(lst[i])…
Truncate List Keeping Last N Elements in Python
Return a new list containing only the last N elements from a sequence, handling edge cases like zero or oversized counts.
def truncate(seq, keep_last_n):
"""Return a new list keeping only the last n elements."""
if keep_last_n <= 0:
return []
return list(seq)[-keep_last_n:]
if __name__ == "__main__":
data = [10, 20, 30, 40, 50, 60]
print(truncate(data, 3))
print(truncate(data, 0))
print(truncate(data…
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.