Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Cycle Through a List Infinitely with itertools
This code uses itertools.cycle to create an infinite iterator over a list and returns the first n items from that cycle.
from itertools import cycle
def demonstrate_cycle(items, cycles=3):
"""
Cycle through a list infinitely using itertools.cycle.
Returns the first n items from the infinite cycle.
"""
cycled = cycle(items)
result = [next(cycled) for _ in range(len(items) * cycles)]
return result
if __name__…
How to Group Consecutive Equal Elements in Python
Group consecutive equal elements in a list into sublists using itertools.groupby.
from itertools import groupby
def group_consecutive(lst):
"""Group consecutive equal elements into sublists."""
return [list(group) for _, group in groupby(lst)]
if __name__ == "__main__":
input_list = [1, 1, 2, 2, 2, 3, 1, 1, 4, 4, 4, 4]
result = group_consecutive(input_list)
print("Input:", inp…
How to Compute the Cartesian Product of Two Lists in Python
Generates all ordered pairs from two lists using itertools.product and prints each combination.
from itertools import product
# Two small input lists
list_a = [1, 2, 3]
list_b = ["x", "y"]
# Compute the Cartesian product
result = list(product(list_a, list_b))
# Display the result
print("Cartesian product of", list_a, "and", list_b, "is:")
for pair in result:
print(pair)
How to Generate Permutations of Length r in Python
Generate and print all r-length permutations of a list using Python's itertools.permutations.
from itertools import permutations
def show_permutations(items, r):
result = list(permutations(items, r))
for perm in result:
print(perm)
print(f"Total: {len(result)}")
if __name__ == "__main__":
data = ["A", "B", "C"]
show_permutations(data, 2)
How to Get All Combinations of a List in Python
Generate and display all combinations of a given length from a list using Python's itertools.combinations.
from itertools import combinations
def list_combinations(items, r):
"""Return all combinations of length r from a list."""
return list(combinations(items, r))
if __name__ == "__main__":
fruits = ["apple", "banana", "cherry", "date"]
pick = 2
result = list_combinations(fruits, pick)
print…
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)
Generate Data with Python Comprehensions and Generators
Shows list, dict compregensions and generator expressions plus a Fibonacci generator to produce data lazily.
# Data generation helpers using comprehensions and generators
from itertools import islice
def fibonacci(limit):
"""Generate Fibonacci numbers up to a limit."""
a, b = 0, 1
while a <= limit:
yield a
a, b = b, a + b
def main():
# List comprehension: squares of even numbers
square…
Group Consecutive Keys in Python with itertools.groupby
Group consecutive equal elements in a list using the itertools.groupby generator, printing each key and its values.
from itertools import groupby
data = [1, 1, 2, 2, 3, 1, 1, 4, 4, 4]
for key, group in groupby(data):
group_list = list(group)
print(f"Key: {key}, Values: {group_list}")
How to Create a Pairwise Generator with zip and tee in Python
Build a memory-efficient generator that yields successive overlapping pairs from any iterable using zip and tee.
from itertools import tee
def pairwise(iterable):
"""Yield successive overlapping pairs from iterable."""
a, b = tee(iterable)
next(b, None)
return zip(a, b)
if __name__ == "__main__":
values = [1, 2, 3, 4, 5]
print(list(pairwise(values)))
print(list(pairwise("hello")))
How to Generate Cartesian Product Combinations in Python
Use itertools.product to generate every combination across multiple iterables, a pattern common for product variant generation.
from itertools import product
def generate_cartesian_combinations(*iterables):
"""Generate all Cartesian product combinations of given iterables."""
return list(product(*iterables))
if __name__ == "__main__":
colors = ["red", "green", "blue"]
sizes = ["S", "M", "L"]
styles = ["t-shirt", "hoodie"]…
How to Generate Combinations with Replacement in Python
Generate all r-length combinations with repetition from a list using the standard library itertools.combinations_with_replacement function.
from itertools import combinations_with_replacement
items = ['A', 'B', 'C']
r = 2
combos = list(combinations_with_replacement(items, r))
for combo in combos:
print(combo)
if __name__ == "__main__":
print(f"Total combinations with replacement: {len(combos)}")
How to Generate Permutations of Length r in Python
Generate all ordered arrangements of length r from a given list of elements using itertools.permutations.
from itertools import permutations
def generate_permutations(elements, r):
"""Generate all r-length permutations of the given elements."""
return list(permutations(elements, r))
if __name__ == "__main__":
elements = ['A', 'B', 'C']
r = 2
result = generate_permutations(elements, r)
print(f"Ele…
How to Implement takewhile Generator in Python
A generator that yields items from an iterable until a condition fails, like itertools.takewhile.
def takewhile(predicate, iterable):
for item in iterable:
if not predicate(item):
break
yield item
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 5, 1, 2, 3]
result = list(takewhile(lambda x: x < 4, numbers))
print(result)
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]
How to Use starmap() to Unpack Tuple Arguments in Python
Use itertools.starmap to apply a function to each tuple in an iterable, unpacking tuple elements as separate arguments and returning an iterator of results.
from itertools import starmap
def multiply(a, b):
return a * b
if __name__ == "__main__":
pairs = [(2, 3), (4, 5), (6, 7), (8, 9)]
results = list(starmap(multiply, pairs))
print(results)
How to generate combinations in Python with itertools
Generate all unique combinations of r items from a given list using itertools.combinations.
import itertools
def combinations_generator(items, r):
return list(itertools.combinations(items, r))
if __name__ == "__main__":
items = ['A', 'B', 'C', 'D']
r = 2
result = combinations_generator(items, r)
for combo in result:
print(combo)
print(f"Total: {len(result)} combinations of {…
How to skip items until a condition is met in Python
Use itertools.dropwhile to skip leading elements while a predicate returns true, then yield the rest of the sequence unchanged.
def is_negative(x):
return x < 0
numbers = [-3, -1, 0, 5, 2, -8, 7]
result = list(itertools.dropwhile(is_negative, numbers))
print(f"Original: {numbers}")
print(f"After dropwhile: {result}")
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 round-robin load balancing in Python
Implement a client-side round-robin load balancer that distributes requests sequentially across a list of mock servers using itertools.cycle.
import itertools
import random
class MockServer:
def __init__(self, name):
self.name = name
def handle_request(self, request_id):
return f"Server {self.name} handled request #{request_id}"
class RoundRobinLoadBalancer:
def __init__(self, servers):
self.servers = servers
…
Grid Search Hyperparameters in Python
Perform exhaustive grid search over hyperparameter combinations using itertools.product and a scoring function.
import itertools
def grid_search(param_grid, score_fn):
"""Perform exhaustive grid search over hyperparameter combinations."""
keys = param_grid.keys()
names = list(keys)
values = [param_grid[name] for name in names]
results = []
for combination in itertools.product(*values):
params =…
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.