Python Code Examples

Here are some Python code examples demonstrating various language features.

List Comprehensions

List comprehensions provide a concise way to create lists.

	squares = [x**2 for x in range(10)]
	evens = [x for x in range(20) if x % 2 == 0]
	print(squares)
	print(evens)

Decorators

Decorators are a way to modify or enhance functions without changing their definition.

def timer(func):
    import time
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} took {end - start:.2f}s")
        return result
    return wrapper

@timer
def slow_function():
    import time
    time.sleep(1)