Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Find the Index of a Substring or Return a Default in Python
Finds the index of a substring using str.find() and returns a specified default value instead of -1 when the substring is not found.
def find_substring_or_default(text, substring, default=-1):
index = text.find(substring)
return index if index != -1 else default
if __name__ == "__main__":
text = "The quick brown fox jumps over the lazy dog"
print(find_substring_or_default(text, "brown"))
print(find_substring_or_default(text, "c…
Enumerate a Python List with a Custom Start Index
Iterate over a list with an index that starts at a custom value (like 5) using Python's built-in enumerate() function with the start parameter.
fruits = ["apple", "banana", "cherry", "date"]
for index, fruit in enumerate(fruits, start=5):
print(f"{index}: {fruit}")
Find All Occurrences of an Item in a Python List
Loop through a list with enumerate() to collect the index of every match for a target value.
def find_all(data, target):
"""Return indices of every occurrence of target in a list."""
indices = []
for index, item in enumerate(data):
if item == target:
indices.append(index)
return indices
if __name__ == "__main__":
sample = [10, 20, 30, 20, 40, 20, 50]
target_value …
How to Calculate a Cumulative Sum in Python
Build a new list where each element equals the running total of all numbers up to that index in the original list.
numbers = [1, 2, 3, 4, 5]
cumulative_sum = []
running_total = 0
for num in numbers:
running_total += num
cumulative_sum.append(running_total)
print(cumulative_sum)
How to Find the Third Smallest Element in a Python List
Find the third smallest distinct value in a Python list by sorting unique elements and returning the third index.
def find_third_smallest(numbers):
if len(numbers) < 3:
return None
unique_sorted = sorted(set(numbers))
if len(unique_sorted) < 3:
return None
return unique_sorted[2]
if __name__ == "__main__":
sample = [5, 2, 8, 2, 9, 1, 7, 3]
result = find_third_smallest(sampl…
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 Swap Two Indices in a Python List
Swap two elements at given indices in a Python list using simultaneous assignment, then return the modified list.
def swap_indices(lst, i, j):
lst[i], lst[j] = lst[j], lst[i]
return lst
if __name__ == "__main__":
my_list = [10, 20, 30, 40, 50]
print("Original list:", my_list)
swapped = swap_indices(my_list, 1, 3)
print("After swapping indices 1 and 3:", swapped)
How to implement binary search in Python
Standalone binary search function that returns the index of a target in a sorted list, or -1 if not found.
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
if __name__ ==…
Build a File Index by Relative Path Hash Map in Python
Recursively walk a directory and map normalized relative paths to absolute file paths using a defaultdict hash map.
import os
from collections import defaultdict
def build_file_index(root_dir):
index = defaultdict(list)
for dirpath, dirnames, filenames in os.walk(root_dir):
for filename in filenames:
full_path = os.path.join(dirpath, filename)
relative_path = os.path.relpath(full_path, roo…
How to Index a List of Records by Unique ID in Python
Build a dictionary that maps each record's unique id to the record itself from a list of dictionaries.
from typing import List, Dict, Any
def index_by_id(records: List[Dict[str, Any]], id_field: str = "id") -> Dict[Any, Dict[str, Any]]:
"""Build a dictionary mapping each record's unique id to the record itself."""
return {record[id_field]: record for record in records}
if __name__ == "__main__":
sample_re…
How to Create a Data Splitter Class in Python
This code defines a DataSplitter class that splits data by index, into chunks, or by a predicate, demonstrating OOP principles in Python.
class DataSplitter:
def __init__(self, data):
self.data = list(data)
def split_by_index(self, index):
return self.data[:index], self.data[index:]
def split_into_chunks(self, chunk_size):
return [self.data[i:i + chunk_size] for i in range(0, len(self.data), chunk_size)]
…
Count Smaller Elements to the Right in Python
Return a list where each index counts how many elements to its right are smaller than that element using a clean O(n²) nested-loop approach.
def count_smaller_elements(arr):
"""
Return a list where result[i] is the number of elements
to the right of arr[i] that are smaller than arr[i].
"""
result = []
for i in range(len(arr)):
count = 0
for j in range(i + 1, len(arr)):
if arr[j] < arr[i]:
…
Find All Indices of a Target Value in a Python List
Returns a list of all indices where a given target value appears in a Python list using a list comprehension with enumerate.
def find_all_indices(arr, target):
return [i for i, value in enumerate(arr) if value == target]
if __name__ == "__main__":
sample_list = [4, 2, 7, 2, 9, 2, 1, 2]
target = 2
result = find_all_indices(sample_list, target)
print(result)
Find First Duplicate Index in Python
Return the index of the first element that appears more than once in a list, using a dictionary for O(n) time.
def find_first_duplicate(arr):
seen = {}
for index, value in enumerate(arr):
if value in seen:
return index
seen[value] = index
return -1
if __name__ == "__main__":
test_array = [3, 5, 2, 8, 5, 1, 2]
result = find_first_duplicate(test_array)
print(f"Array: {test_arr…
Find Maximum Distance Between Identical Elements in Python
Compute the maximum index distance between any two identical elements in a list using a dictionary to track first occurrences.
from collections import defaultdict
def max_distance_between_identical(nums):
first_occurrence = {}
max_dist = 0
for i, num in enumerate(nums):
if num in first_occurrence:
dist = i - first_occurrence[num]
max_dist = max(max_dist, dist)
else:
first_occur…
Find Pivot Index in Python
Locate the index where the sum of elements to the left equals the sum to the right, using a single pass with prefix sums.
def find_pivot_index(nums):
total = sum(nums)
left_sum = 0
for i, num in enumerate(nums):
if left_sum == total - left_sum - num:
return i
left_sum += num
return -1
if __name__ == "__main__":
test_cases = [
[1, 7, 3, 6, 5, 6],
[1, 2, 3],
[2, 1, -…
Find the Equilibrium Index of a List in Python
Find every index in a list where the sum of elements to its left equals the sum to its right, using a single pass.
def find_equilibrium_indexes(arr):
total = sum(arr)
left_sum = 0
indexes = []
for i, num in enumerate(arr):
total -= num
if left_sum == total:
indexes.append(i)
left_sum += num
return indexes
if __name__ == "__main__":
test = [1, 2, 3, -1, 2, 3]
result =…
Find the First Index Where a Condition Is True in Python
Search any iterable for the first element matching a predicate and return its index, or -1 if none match.
def first_true_index(items, condition):
"""Return the first index where condition(item) is True, or -1 if none match."""
for i, item in enumerate(items):
if condition(item):
return i
return -1
if __name__ == "__main__":
numbers = [1, 3, 5, 8, 10, 12]
# Find first number greate…
Find the Last Index Where a Condition Is True in Python
This code scans a sequence from the end and returns the index of the last element that satisfies a given condition, or -1 if none do.
def last_index_where(sequence, condition):
"""Return the index of the last element in sequence that satisfies condition."""
for i in range(len(sequence) - 1, -1, -1):
if condition(sequence[i]):
return i
return -1
if __name__ == "__main__":
numbers = [1, 4, 7, 2, 9, 5, 8, 3]
is_…
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[…
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), …
Enumerate a Generator With a Running Total in Python
A generator that yields each element with its index and a cumulative sum, letting you track a running total as you iterate.
def running_total_enum(iterable):
"""Yields (index, item, running_total) for each element."""
total = 0
for index, item in enumerate(iterable):
total += item
yield index, item, total
if __name__ == "__main__":
numbers = [10, 20, 30, 40, 50]
for idx, value, running_sum in running_to…
How to Create a Line-Numbered Generator with enumerate start in Python
This Python code defines a generator that yields lines prefixed with their index, using enumerate's start parameter to offset numbering.
def line_numbered_lines(lines, start=1):
for idx, line in enumerate(lines, start):
yield f"{idx:3} {line}"
if __name__ == "__main__":
sample = ["first line", "second", "third"]
for numbered in line_numbered_lines(sample, start=10):
print(numbered)
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.