Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
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 Implement the Iterator Protocol in Python
A manual iterator class using __iter__ and __next__, compared with an equivalent generator using yield.
class ManualCounter:
def __init__(self, limit):
self.limit = limit
self.current = 0
def __iter__(self):
return self
def __next__(self):
if self.current >= self.limit:
raise StopIteration
value = self.current
self.current += 1
return valu…
How to Merge Multiple Iterables with a Generator in Python
This code defines a generator function that 'chains' or merges multiple iterables into a single iterator, which is then converted to a list.
def chain(*iterables):
for iterable in iterables:
yield from iterable
def main():
list1 = [1, 2, 3]
tuple1 = (4, 5)
set1 = {6, 7}
string1 = "89"
result = list(chain(list1, tuple1, set1, string1))
print(result)
if __name__ == "__main__":
main()
How to Parse CSV Rows as Generator Dicts in Python
Reads a CSV file and yields each row as a dictionary one at a time using a generator, so the file is processed lazily.
import csv
from pathlib import Path
def csv_to_dicts(filepath):
with open(filepath, mode="r", newline="", encoding="utf-8") as file:
reader = csv.DictReader(file)
for row in reader:
yield row
if __name__ == "__main__":
sample_csv = Path("sample_data.csv")
sample_csv.write_text…
How to Repeat a Generator Cycle Single Value in Python
Build a generator that repeats a single value across multiple cycles, each cycle adding an extra repetition to mark its completion.
def repeat_with_cycle(value, cycle_limit, repetitions):
"""
Repeats a single value until reaching a cycle limit,
then yields the value one more time to demonstrate a full cycle.
Args:
value: The single value to repeat.
cycle_limit: Number of repetitions per cycle.
repetitio…
How to Use Comprehensions and Generators in Python
Demonstrate list, set, and dictionary comprehensions plus generator expressions and generator functions in one beginner-friendly script.
def demonstrate_comprehensions_generators():
# List comprehension: transform and filter in one line
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = [num ** 2 for num in numbers if num % 2 == 0]
print(f"Square of even numbers (list comprehension): {squares}")
# Set comprehension: unique values
…
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}")
Python Generator to Filter Duplicates with a Seen Set
A lazily-evaluated generator function that yields only the first occurrence of each item, using a set to track seen values.
def unique_generator(items):
seen = set()
for item in items:
if item not in seen:
seen.add(item)
yield item
if __name__ == "__main__":
data = [1, 2, 2, 3, 3, 3, 4, 5, 5]
result = list(unique_generator(data))
print(result)
How to Stream Tokens from a Mock LLM in Python
Simulate real-time LLM streaming by yielding tokens one at a time with a delay, making it easy to test streaming UIs.
import time
from typing import Generator
def stream_tokens(text: str, delay: float = 0.05) -> Generator[str, None, None]:
"""Simulate an LLM streaming tokens word by word."""
for word in text.split():
yield word
time.sleep(delay)
if __name__ == "__main__":
sample = "Hello world! This is…
How to Paginate a List with a Generator in Python
Define a generator that yields list items in fixed-size pages, simulating pagination for cloud resource APIs.
from typing import List, Iterator
def paginate_generator(items: List[str], page_size: int = 3) -> Iterator[List[str]]:
"""Yield items in fixed-size chunks with a mock pagination pattern."""
for i in range(0, len(items), page_size):
yield items[i:i + page_size]
if __name__ == "__main__":
resources…
asyncio sleep cooperative scheduling demo in Python
This demo shows how asyncio.sleep yields control between concurrent tasks, letting multiple workers interleave their ticks.
import asyncio
async def worker(name, delay):
for i in range(3):
print(f"{name}: tick {i}")
await asyncio.sleep(delay)
return f"{name} done"
async def main():
tasks = [
asyncio.create_task(worker("A", 0.1)),
asyncio.create_task(worker("B", 0.2)),
asyncio.create_tas…
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.