Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
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)}")
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}")
Separate Evens and Odds into Two Lists in Python
Split a list of numbers into two lists containing even and odd numbers using a simple loop and the modulo operator.
def separate_evens_odds(numbers):
evens = []
odds = []
for num in numbers:
if num % 2 == 0:
evens.append(num)
else:
odds.append(num)
return evens, odds
if __name__ == "__main__":
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens, odds = separate_evens_odds(nu…
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}")
Pair Elements with Next Cyclic Neighbor in Python
Create tuples pairing every element with its next element, wrapping around to the first element for the last one.
def cyclic_pairs(lst):
if not lst:
return []
return [(lst[i], lst[(i + 1) % len(lst)]) for i in range(len(lst))]
if __name__ == "__main__":
sample = [1, 2, 3, 4, 5]
result = cyclic_pairs(sample)
print(result)
How to shard output by primary key hash mod N in Python
This code computes a consistent shard index for any primary key string using an MD5 hash mod the number of shards, enabling stable key-based data distribution.
import hashlib
def shard_id(primary_key: str, num_shards: int) -> int:
"""Return the shard index for a primary key using MD5 hash mod N."""
digest = hashlib.md5(primary_key.encode("utf-8")).hexdigest()
hash_int = int(digest, 16)
return hash_int % num_shards
if __name__ == "__main__":
keys = ["use…
Partition Data by Hash Key Mod N in Python
Returns a partition index for a string key by hashing it with MD5 and taking modulo N, then groups sample keys into partitions.
import hashlib
def partition_key(key: str, num_partitions: int) -> int:
"""Return partition index for key using MD5 hash mod N."""
digest = hashlib.md5(key.encode()).hexdigest()
return int(digest, 16) % num_partitions
if __name__ == "__main__":
keys = ["alice", "bob", "carol", "dave", "eve"]
nu…
How to Hash a User ID to an Experiment Bucket in Python
Deterministically map a user ID to one of N experiment buckets using MD5 hashing and modulo arithmetic.
import hashlib
def hash_to_bucket(user_id: str, num_buckets: int = 10) -> int:
"""Deterministically map a user_id to a bucket (0 to num_buckets-1)."""
digest = hashlib.md5(user_id.encode("utf-8")).hexdigest()
return int(digest[:8], 16) % num_buckets
if __name__ == "__main__":
# Mock experiment: split…
How to Shard Data by User ID Hash in Python
Deterministically map user IDs to shard indexes using an MD5 hash modulo the shard count in Python.
import hashlib
def shard_id(user_id: str, num_shards: int = 4) -> int:
"""Deterministically map a user_id to a shard index using MD5."""
digest = hashlib.md5(user_id.encode("utf-8")).hexdigest()
return int(digest[:8], 16) % num_shards
if __name__ == "__main__":
user_ids = ["alice", "bob", "carol", "d…
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.