# Basic list comprehension
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# With condition
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# Nested comprehension
matrix = [[i*j for j in range(3)] for i in range(3)]
# [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
#decorators
def timer(func):
def wrapper(*args, **kwargs):
import time
start = [Link]()
result = func(*args, **kwargs)
print(f"{func.__name__} took {[Link]() - start:.4f}s")
return result
return wrapper
@timer
def slow_function():
[Link](1)
return "Done"
slow_function() # Prints execution time
class FileManager:
def __init__(self, filename, mode):
[Link] = filename
[Link] = mode
def __enter__(self):
[Link] = open([Link], [Link])
return [Link]
def __exit__(self, exc_type, exc_val, exc_tb):
[Link]()
with FileManager('[Link]', 'w') as f:
[Link]('Hello World')
numbers = [1, 2, 3, 4, 5, 6]
# Filter with lambda
evens = list(filter(lambda x: x % 2 == 0, numbers))
# [2, 4, 6]
# Map with lambda
squared = list(map(lambda x: x**2, numbers))
# [1, 4, 9, 16, 25, 36]
# Reduce
from functools import reduce
product = reduce(lambda x, y: x * y, numbers)
# 720