Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
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 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 Longest Consecutive Run in an Unsorted List in Python
Find the length of the longest sequence of consecutive integers in an unsorted list using a set and a linear scan.
def longest_run(nums):
if not nums:
return 0
num_set = set(nums)
longest = 0
for num in num_set:
# Only start counting from the smallest number in a sequence
if num - 1 not in num_set:
current = num
length = 1
while current + 1 in num_set:
…
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 Median of Two Sorted Arrays in Python
Merges two sorted arrays with a two-pointer walk and returns the median of the combined sorted sequence.
def median_of_two_sorted_arrays(nums1, nums2):
merged = []
i = j = 0
while i < len(nums1) and j < len(nums2):
if nums1[i] <= nums2[j]:
merged.append(nums1[i])
i += 1
else:
merged.append(nums2[j])
j += 1
merged.extend(nums1[i:])
merged.…
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 =…
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:
…
Merge Two Sorted Arrays Without Extra Space in Python
Merge two sorted arrays in-place from the end, using the trailing zeros in the first array to avoid extra space.
def merge_sorted(arr1, arr2):
m, n = len(arr1), len(arr2)
i, j = m - 1, n - 1
while j >= 0:
if i >= 0 and arr1[i] > arr2[j]:
arr1[i + j + 1] = arr1[i]
i -= 1
else:
arr1[i + j + 1] = arr2[j]
j -= 1
return arr1
if __name__ == "__main__":
…
How to Explode an Array Field into Multiple Rows in Python
This code flattens a list of dictionaries by exploding each array field value into its own row, duplicating the other fields as needed.
from collections import defaultdict
data = [
{"id": 1, "name": "Alice", "tags": ["python", "data", "ai"]},
{"id": 2, "name": "Bob", "tags": ["web", "devops"]},
{"id": 3, "name": "Carol", "tags": []},
]
def explode_array_field(records, array_field):
result = []
for record in records:
for v…
How to Group Rows by Key into Nested Arrays in Python
This code groups rows in a list of dictionaries by a specified key and returns a dictionary with each key mapped to a list of values from another key.
from collections import defaultdict
def implode_rows(rows, key, value_key):
grouped = defaultdict(list)
for row in rows:
grouped[row[key]].append(row[value_key])
return dict(grouped)
if __name__ == "__main__":
data = [
{"category": "fruit", "item": "apple"},
{"category": "fr…
How to Explode an Array Column in Python
This code demonstrates a mock explode operation that converts an array column into multiple rows, similar to Spark's explode function.
import json
def explode_array_column(data, column):
"""Mock explode: split array column into multiple rows."""
exploded = []
for row in data:
values = row.get(column, [])
for value in values:
new_row = dict(row)
new_row[column] = value
exploded.append(n…
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.