Functions & basics
Reusable building blocks — parameters, returns, scope, and clear function design.
Chain Generators with yield from in Python
Combine multiple generators into one seamless sequence using the `yield from` delegation syntax in Python.
def numbers():
yield 1
yield 2
yield 3
def letters():
yield 'a'
yield 'b'
yield 'c'
def combined():
yield from numbers()
yield from letters()
if __name__ == "__main__":
print(list(combined()))
How to Convert a List to an Iterator in Python with iter()
This code converts a list into an iterator using the built-in iter() function and retrieves items sequentially with next(), handling exhaustion with StopIteration.
def main():
# Original list
fruits = ["apple", "banana", "cherry"]
# Convert the list to an iterator using iter()
fruit_iterator = iter(fruits)
# Retrieve items one at a time with next()
print(next(fruit_iterator)) # apple
print(next(fruit_iterator)) # banana
print(next(fruit_iterat…
How to Create Generator Functions with yield in Python
Create a memory-efficient generator function using yield to produce a Fibonacci sequence up to a limit.
def fibonacci_sequence(limit):
"""Generate Fibonacci numbers up to a given limit."""
a, b = 0, 1
while a <= limit:
yield a
a, b = b, a + b
if __name__ == "__main__":
fib_gen = fibonacci_sequence(100)
for number in fib_gen:
print(number, end=" ")
print()
Browse by section
Each section groups closely related Python snippets.
Functions & basics — Python code examples
What you will find here
This page collects functions & basics snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
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.