Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
How to Build a Sliding Window Generator in Python
Create a generator that yields fixed-size overlapping slices of a sequence, useful for efficient windowed iteration.
def sliding_window(sequence, size):
for i in range(len(sequence) - size + 1):
yield sequence[i:i + size]
if __name__ == "__main__":
data = [1, 2, 3, 4, 5]
n = 3
for window in sliding_window(data, n):
print(window)
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)
How to Delegate Iteration to a Subgenerator with yield from in Python
Use yield from to delegate iteration from one generator to a subgenerator, flattening nested generator output into a single sequence.
def subgenerator():
yield "first"
yield "second"
yield "third"
def delegate():
yield "before delegation"
yield from subgenerator()
yield "after delegation"
if __name__ == "__main__":
for item in delegate():
print(item)
How to Generate Fibonacci Numbers in Python Without Recursion
Build an efficient infinite Fibonacci sequence using a generator function with O(1) memory and no recursion overhead.
def fib(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
if __name__ == "__main__":
count = 10
result = list(fib(count))
print(result)
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 Lazily Transform Items in Python with a Generator
Map a transform function over an iterable lazily with a generator so items are processed on demand, not up front.
def lazy_map(items, transform):
for item in items:
yield transform(item)
def double(x):
return x * 2
def upper(s):
return s.upper()
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 5]
doubled = lazy_map(numbers, double)
print("Doubled numbers:", end=" ")
for value in doubled:
…
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}")
List Comprehension to Filter Even Numbers in Python
Creates a new list containing only the even numbers from an existing list using a list comprehension with a condition.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [n for n in numbers if n % 2 == 0]
print(f"Original: {numbers}")
print(f"Even numbers: {even_numbers}")
Python Comprehensions and Generators for Beginners
Learn list, dict, and set comprehensions plus generator expressions and generator functions with clear, runnable examples.
# Demonstrates list comprehensions, dict comprehensions, set comprehensions, and generators
def demonstrate_comprehensions():
# List comprehension: squares of even numbers
numbers = range(1, 11)
even_squares = [n ** 2 for n in numbers if n % 2 == 0]
# Dict comprehension: number to its factorial
…
How to Iterate Redis Keys with SCAN in Python
Iterate all Redis keys matching a pattern using the SCAN command with a mock client to simulate pagination.
import redis
def scan_keys(client, pattern="*", count=10):
keys = []
cursor = 0
while True:
cursor, batch = client.scan(cursor=cursor, match=pattern, count=count)
keys.extend(batch)
if cursor == 0:
break
return keys
if __name__ == "__main__":
# Mock Redis clien…
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.