Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
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…
How to Group a List into Chunks in Python
Split a list into smaller groups of a fixed size using a reusable function with a default parameter.
def make_groups(numbers, group_size=2):
"""Splits a list into smaller groups of a given size."""
groups = []
for i in range(0, len(numbers), group_size):
groups.append(numbers[i:i + group_size])
return groups
if __name__ == "__main__":
data = [1, 2, 3, 4, 5, 6, 7]
print("Default size…
Parse Fixed Width Data File by Column Slices in Python
Extract fields from fixed-width text by slicing each line at defined column offsets, with a dictionary describing the boundaries.
from pathlib import Path
def parse_fixed_width(data: str, slices: dict[str, tuple[int, int]]) -> list[dict[str, str]]:
lines = data.strip().splitlines()
records = []
for line in lines:
record = {}
for name, (start, end) in slices.items():
record[name] = line[start:end].strip()…
How to Apply a Function to Sliding Window Slices in Python
This Python code applies a given function to every contiguous window of a specified size in a list, returning a list of results.
def apply_to_sliding_windows(data, window_size, func):
return [func(data[i:i + window_size]) for i in range(len(data) - window_size + 1)]
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 5, 6]
window_size = 3
results = apply_to_sliding_windows(numbers, window_size, sum)
print(results)
results…
How to Implement a Moving Average from a Data Stream in Python
Implement a MovingAverage class using a deque and running sum to compute the average of the last k values from a continuous data stream.
from collections import deque
class MovingAverage:
def __init__(self, size):
self.size = size
self.queue = deque()
self.window_sum = 0
def next(self, val):
self.queue.append(val)
self.window_sum += val
if len(self.queue) > self.size:
self.window_su…
How to Implement a Recent Counter with a Deque in Python
Implements a RecentCounter class that uses a deque to count ping requests within the last 3000 milliseconds.
from collections import deque
import time
class RecentCounter:
def __init__(self):
self.hits = deque()
def ping(self, t: int) -> int:
self.hits.append(t)
while self.hits and self.hits[0] < t - 3000:
self.hits.popleft()
return len(self.hits)
if __name__ == "__mai…
How to Rotate an Array by k Steps in Python
This code rotates a list to the right by k positions using modulo arithmetic to handle k larger than the list length.
def rotate_array(nums, k):
if not nums:
return []
n = len(nums)
k = k % n
return nums[-k:] + nums[:-k] if k else nums[:]
if __name__ == "__main__":
arr = [1, 2, 3, 4, 5, 6]
k = 2
result = rotate_array(arr, k)
print(f"Original: {arr}")
print(f"Rotated by {k}: {result}")
How to partition a list into n nearly equal parts in Python
Divide a list into n contiguous chunks of nearly equal size using an average-length calculation that distributes the remainder evenly.
def partition(lst, n):
"""Partition a list into n nearly equal contiguous parts."""
if n <= 0:
raise ValueError("n must be positive")
if not lst:
return [[] for _ in range(n)]
parts = []
avg = len(lst) / n
last_idx = 0.0
while last_idx < len(lst):
end_idx =…
Remove item at index without pop in Python
Remove an item at a given index from a list without using pop by slicing the list around the index.
def remove_at_index(lst, index):
"""Remove item at index and return the new list."""
if index < 0 or index >= len(lst):
raise IndexError("Index out of range")
return lst[:index] + lst[index + 1:]
if __name__ == "__main__":
items = [10, 20, 30, 40, 50]
result = remove_at_index(items, 2)
…
Reorder a List by Odd Even Indices in Python
Splits a list into two sublists based on 1-based index parity, then concatenates odd-indexed elements before even-indexed ones.
def reorder_by_odd_even(items):
"""Reorders a list so that elements at odd indices come first,
followed by elements at even indices (1-based).
Example: [0,1,2,3,4,5,6] -> [1,3,5,0,2,4,6]
"""
odds = [items[i] for i in range(1, len(items), 2)]
evens = [items[i] for i in range(0, len(items), …
Batch Rows in Chunks with a Generator in Python
Group a list of row dicts into fixed-size chunks using a generator that yields one slice per call.
from typing import Iterator, List
def batch_rows(rows: List[dict], batch_size: int) -> Iterator[List[dict]]:
for i in range(0, len(rows), batch_size):
yield rows[i:i + batch_size]
if __name__ == "__main__":
sample_rows = [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"},
…
Chunk an Iterable into Batches with a Generator in Python
Yield fixed-size batches from any iterable lazily using itertools.islice inside a generator function.
from itertools import islice
def chunked(iterable, size):
iterator = iter(iterable)
while True:
batch = list(islice(iterator, size))
if not batch:
break
yield batch
if __name__ == "__main__":
data = range(10)
for batch in chunked(data, 3):
print(batch)
How to Build a Sliding Window Generator in Python
Create a generator that yields fixed-size overlapping slices of a sequence, useful for efficient windowed iteration.
def sliding_window(sequence, size):
for i in range(len(sequence) - size + 1):
yield sequence[i:i + size]
if __name__ == "__main__":
data = [1, 2, 3, 4, 5]
n = 3
for window in sliding_window(data, n):
print(window)
How to Slice a Generator with islice in Python
Use itertools.islice to take the first n items from any iterable without materializing the whole sequence into a list.
from itertools import islice
def first_n(iterable, n):
"""Return the first n items from an iterable."""
return list(islice(iterable, n))
if __name__ == "__main__":
numbers = range(10, 100) # large iterable
result = first_n(numbers, 5)
print(result) # [10, 11, 12, 13, 14]
Take n items from an infinite Python generator
Uses itertools.islice to lazily take exactly n items from an infinite generator without exhausting it.
from itertools import islice
def count_up_from(start=0):
n = start
while True:
yield n
n += 1
def take_n(generator, count):
return list(islice(generator, count))
if __name__ == "__main__":
gen = count_up_from(10)
result = take_n(gen, 5)
print(result)
How to Implement a Sliding Window Average in Python
Compute the average of the most recent N values in a stream using a bounded deque, efficiently updating the total as new values arrive.
from collections import deque
class SlidingWindowAverage:
def __init__(self, window_size):
self.window_size = window_size
self.window = deque(maxlen=window_size)
self.total = 0
def add(self, value):
if len(self.window) == self.window_size:
self.total -= self.windo…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
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.