Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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 Sample Random Items Without Replacement in Python
Select k random unique items from a sequence using random.sample for uniform, non-repeating selection.
import random
def sample_without_replacement(population, k):
"""Return k random items from population without replacement."""
if k > len(population):
raise ValueError("k cannot exceed population size")
# Use random.sample for O(k) time, no mutation of the original
return random.sample(populati…
How to Search a Rotated Sorted List in Python
Binary search a pivot-rotated sorted list for a target value and return its index in O(log n) time.
from typing import List
def search_rotated(nums: List[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
# left half is sorted
if nums[left] <= nums[mid]:
if nums[…
How to Solve Daily Temperatures Days Until Warmer in Python
Compute the number of days until a warmer temperature for each day using a monotonic stack.
def daily_temperatures(temps):
n = len(temps)
result = [0] * n
stack = []
for i, temp in enumerate(temps):
while stack and temps[stack[-1]] < temp:
prev_idx = stack.pop()
result[prev_idx] = i - prev_idx
stack.append(i)
return result
if __name__ == …
How to Solve the Trapping Rain Water Problem in Python
Compute the total water trapped between elevation bars using a two-pointer O(n) algorithm.
def trap(height):
if not height:
return 0
left, right = 0, len(height) - 1
left_max, right_max = 0, 0
water = 0
while left < right:
if height[left] < height[right]:
if height[left] >= left_max:
left_max = height[left]
else:
…
How to Sort Colors (Dutch National Flag) in Python
In-place sorting of a list of 0s, 1s, and 2s using the Dutch National Flag algorithm with O(n) time and O(1) space.
def sort_colors(nums):
low, mid, high = 0, 0, len(nums) - 1
while mid <= high:
if nums[mid] == 0:
nums[low], nums[mid] = nums[mid], nums[low]
low += 1
mid += 1
elif nums[mid] == 1:
mid += 1
else: # nums[mid] == 2
nums[mid], n…
How to compress consecutive numbers into range strings in Python
Convert a sorted list of consecutive integers into compact range strings like '1-3', '5-6', and '15'.
def compress_ranges(nums):
"""Convert a list of sorted consecutive numbers into range strings."""
if not nums:
return []
ranges = []
start = prev = nums[0]
for num in nums[1:]:
if num == prev + 1:
prev = num
else:
if start == prev:
…
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 =…
How to solve the stock span problem in Python
Calculate the stock span for each day's price using a monotonic stack in O(n) time.
def stock_span(prices):
span = [1] * len(prices)
stack = []
for i in range(len(prices)):
while stack and prices[stack[-1]] <= prices[i]:
stack.pop()
span[i] = i - stack[-1] if stack else i + 1
stack.append(i)
return span
if __name__ == "__main__":
pric…
Implement Queue Using Two Stacks in Python
Python class that implements a FIFO queue using two stacks, with enqueue, dequeue, peek, and emptiness checks.
class QueueUsingStacks:
def __init__(self):
self.stack_in = []
self.stack_out = []
def enqueue(self, value):
self.stack_in.append(value)
def dequeue(self):
if not self.stack_out:
while self.stack_in:
self.stack_out.append(self.stack_in.pop())
…
Insert Multiple Values Into a Sorted List in Python
Insert multiple values into an already-sorted list while keeping it sorted using the bisect.insort function.
import bisect
def insert_sorted(sorted_list, values):
for value in values:
bisect.insort(sorted_list, value)
return sorted_list
if __name__ == "__main__":
original = [1, 3, 5, 7, 9]
new_values = [4, 6, 2, 8, 0]
result = insert_sorted(original, new_values)
print(f"Original: {original}"…
Insert an Element Every n Positions in Python
Insert a given element before or after every n-th position in a Python list, returning a new list with the placements applied.
def insert_every_n(seq, element, n, position="after"):
"""Insert an element before or after every n-th position in a list.
Args:
seq: Input list
element: Element to insert
n: Insert every n positions (n > 0)
position: 'before' or 'after' (default: 'after')
Returns:
…
Move Zeroes to End in Python Maintaining Order
In-place algorithm that moves all zeroes to the end of a list while preserving the relative order of non-zero elements.
def move_zeroes(nums):
non_zero_index = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[non_zero_index], nums[i] = nums[i], nums[non_zero_index]
non_zero_index += 1
return nums
if __name__ == "__main__":
example = [0, 1, 0, 3, 12]
result = move_zeroes(example)
…
Product of All Elements Except Self in Python
Given a list of integers, return a list where each element is the product of all other elements except itself, using prefix and suffix products in O(n) time and O(1) extra space.
def product_except_self(nums):
n = len(nums)
result = [1] * n
left_product = 1
for i in range(n):
result[i] = left_product
left_product *= nums[i]
right_product = 1
for i in range(n - 1, -1, -1):
result[i] *= right_product
right_product *= nums[i]
…
Quickselect in Python: Find the kth Smallest Element
Python implementation of the Quickselect algorithm to find the kth smallest element in an unsorted list with average O(n) time complexity.
def quickselect(arr, k):
"""
Returns the k-th smallest element (0-indexed) using Quickselect.
Average: O(n), Worst: O(n^2)
"""
if len(arr) == 1:
return arr[0]
pivot = arr[-1]
left = [x for x in arr[:-1] if x <= pivot]
right = [x for x in arr[:-1] if x > pivot]
if k < len(l…
Rearrange array alternately max min in Python
Rearranges a sorted list so its elements alternate between the current maximum and current minimum using two pointers in O(n) time.
def rearrange_alternately(arr):
"""
Rearrange sorted array so elements alternate: max, min, next max, next min...
Returns a new list in O(n) time using O(n) space.
"""
n = len(arr)
result = []
left, right = 0, n - 1
while left <= right:
if left == right:
result.appen…
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), …
Segregate Negative Numbers Before Positives in Python
Reorders a list so all negative numbers appear before non-negative numbers while preserving the original relative order of elements.
def segregate_negatives(numbers):
"""Segregate negatives before positives without altering relative order."""
negatives = [n for n in numbers if n < 0]
positives = [n for n in numbers if n >= 0]
return negatives + positives
if __name__ == "__main__":
sample = [3, -1, 4, -5, 2, -9, 0]
result =…
Set Matrix Zeroes in Python: Markers List Grid Demo
Given a matrix, this code finds all rows and columns that contain a zero and sets every element in those rows and columns to zero, using boolean marker arrays.
def set_zeroes(matrix):
rows, cols = len(matrix), len(matrix[0])
row_markers = [False] * rows
col_markers = [False] * cols
# First pass: record which rows and columns contain zeros
for i in range(rows):
for j in range(cols):
if matrix[i][j] == 0:
row_markers[i] …
Simplify a File Path in Python with a Stack
Uses a stack to normalize an absolute Unix path by handling '.', '..', and duplicate slashes.
from pathlib import PurePosixPath
def simplify_path(path: str) -> str:
tokens = path.split('/')
stack = []
for token in tokens:
if not token or token == '.':
continue
if token == '..':
if stack:
stack.pop()
else:
stack.append…
Split a String into Multiple Lines by Width in Python
Demonstrates a word-wrap algorithm that splits a message into rows without exceeding a maximum width.
def split_message(text, max_width):
words = text.split()
rows = []
current_row = []
for word in words:
if len(" ".join(current_row + [word])) > max_width:
rows.append(" ".join(current_row))
current_row = [word]
else:
current_row.append(word)
if …
Stable sort preserving equal order demo in Python
Demonstrates Python's stable sort, showing that elements with equal sort keys retain their original relative order.
from operator import itemgetter
def stable_sort_demo():
data = [(3, "first"), (1, "second"), (3, "third"), (1, "fourth"), (2, "fifth")]
print("Original:", data)
# Sort by first element (the tuple's first value), keeping relative order of equal items
sorted_data = sorted(data, key=itemgetter(0))
…
Take While Predicate True From Start in Python
Create a custom take_while function that collects elements from an iterable until a predicate returns False, then stops.
def take_while(predicate, iterable):
"""Return elements from iterable until the predicate becomes False."""
result = []
for item in iterable:
if predicate(item):
result.append(item)
else:
break
return result
if __name__ == "__main__":
numbers = [2, 4, 6, 7,…
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.