Lists & loops
Iterate, transform, and combine sequences with readable loop patterns.
How to Check if a List is Sorted in Descending Order in Python
This code defines a function that returns True if a given list is sorted in descending order, using a generator expression with all() to compare each adjacent pair.
def is_descending(lst):
"""Return True if list is sorted in descending order."""
return all(lst[i] >= lst[i + 1] for i in range(len(lst) - 1))
if __name__ == "__main__":
test_cases = [
[5, 4, 3, 2, 1],
[3, 3, 2, 1],
[1, 2, 3],
[10, 8, 9],
[]
]
for case in …
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 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 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 …
How to Truncate a List to Max Length in Python (Keep Head)
This code returns a new list containing only the first max_length items from the original list, using Python's slice syntax.
from typing import List
def truncate_head(lst: List[object], max_length: int) -> List[object]:
"""Return a new list with at most max_length items from the head."""
if max_length < 0:
raise ValueError("max_length must be non-negative")
return lst[:max_length]
if __name__ == "__main__":
# Examp…
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 unzip a list of pairs into two lists in Python
Split a list of (a, b) tuples into two separate lists by iterating with a for loop and appending each element to its own output list.
def unzip(pairs):
"""Split a list of (a, b) pairs into two separate lists."""
if not pairs:
return [], []
firsts = []
seconds = []
for a, b in pairs:
firsts.append(a)
seconds.append(b)
return firsts, seconds
if __name__ == "__main__":
pairs = [(1, 'a'), (…
Pairwise Adjacent Differences in a Python List
Computes the absolute differences between each pair of adjacent elements in a list using a concise list comprehension.
def adjacent_differences(nums):
"""Return list of absolute differences between adjacent elements."""
return [abs(nums[i] - nums[i + 1]) for i in range(len(nums) - 1)]
if __name__ == "__main__":
sample = [3, 7, 2, 9, 5]
diffs = adjacent_differences(sample)
print("Original list:", sample)
print…
Separate Evens and Odds into Two Lists in Python
Split a list of numbers into two lists containing even and odd numbers using a simple loop and the modulo operator.
def separate_evens_odds(numbers):
evens = []
odds = []
for num in numbers:
if num % 2 == 0:
evens.append(num)
else:
odds.append(num)
return evens, odds
if __name__ == "__main__":
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens, odds = separate_evens_odds(nu…
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.