Python Snippets
Useful Python code snippets for common programming tasks
List Comprehension
pythonCreate lists using concise list comprehension syntax
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers if x % 2 == 0]
# Result: [4, 16]Context Manager
pythonSafe file handling with context manager
with open('file.txt', 'r') as file:
content = file.read()
# File is automatically closed after this blockDecorators
pythonFunction decorators for code reuse
def timer(func):
def wrapper(*args, **kwargs):
import time
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f'{func.__name__} took {end-start} seconds')
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
return 'Done!'Generator Function
pythonMemory efficient iteration with generators
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
# Use the generator
for num in fibonacci(5):
print(num)
# Output: 0, 1, 1, 2, 3