Lists & loops
Iterate, transform, and combine sequences with readable loop patterns.
How to Compute Sliding Window Sum of Size k in Python
Compute the sum of every contiguous subarray of a fixed size k using an efficient O(n) sliding window technique.
def sliding_window_sum(nums, k):
"""Return a list of sums for each contiguous subarray of size k."""
if not nums or k <= 0 or k > len(nums):
return []
result = []
window_sum = sum(nums[:k])
result.append(window_sum)
for i in range(k, len(nums)):
window_sum += nums[i] -…
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 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 Rotate a List in Python
Rotate a list to the right by k positions using Python's list slicing and modulo arithmetic.
def rotate_list_right(lst, k):
if not lst:
return lst
k = k % len(lst)
return lst[-k:] + lst[:-k] if k != 0 else lst
if __name__ == "__main__":
sample = [1, 2, 3, 4, 5, 6, 7]
for k in [0, 1, 3, 8, 20]:
print(f"k={k}: {rotate_list_right(sample, k)}")
How to Split a List at the First Occurrence of a Value in Python
This function splits a list into two parts at the first occurrence of a given value, returning the left and right portions.
def split_at_first(lst, value):
try:
idx = lst.index(value)
return lst[:idx], lst[idx:]
except ValueError:
return lst, []
if __name__ == "__main__":
sample = [1, 2, 3, 4, 3, 5]
value = 3
left, right = split_at_first(sample, value)
print("Left:", left)
print("Right:"…
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 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…
Rotate List Left by k Positions in Python
Rotates a list left by k positions using slicing and modulo arithmetic to handle large k safely.
def rotate_left(lst, k):
if not lst:
return []
k = k % len(lst)
return lst[k:] + lst[:k]
if __name__ == "__main__":
my_list = [1, 2, 3, 4, 5]
k = 2
result = rotate_left(my_list, k)
print(f"Original: {my_list}")
print(f"After rotating left by {k}: {result}")
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.