Comprehensions provide a concise way to create collections. They are faster and more readable than traditional for loops.
Example:
Python
# List Comprehension: [expression for item in iterable]
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
# Dictionary Comprehension: {key: value for item in iterable}
prices = {"apple": 1, "banana": 2}
double_prices = {k: v*2 for k, v in prices.items()}
next()).yield instead of return. They generate values on the fly, saving massive amounts of memory.Example:
Python
def count_up_to(n):
i = 1
while i <= n:
yield i # Pauses here and returns value
i += 1
counter = count_up_to(1000000) # Memory efficient!
A closure is a nested function that “remembers” the values from its enclosing scope even after the outer function has finished executing.
Example:
Python
def multiplier(n):
def multiply(x):
return x * n
return multiply
times3 = multiplier(3)
print(times3(10)) # 30
Decorators allow you to modify or “wrap” the behavior of a function without changing its source code. They are commonly used for logging, timing, or authentication.
Example:
Python
def my_decorator(func):
def wrapper():
print("Something before.")
func()
print("Something after.")
return wrapper
@my_decorator
def say_hi():
print("Hi!")
Context managers handle the setup and teardown of resources (like opening and closing files). You implement them using the with statement.
Asynchronous programming allows your code to handle multiple tasks concurrently without needing multiple CPU cores. It is widely used in web servers and network applications.
Example:
Python
import asyncio
async def say_hello():
print("Hello...")
await asyncio.sleep(1) # Non-blocking sleep
print("...World!")
asyncio.run(say_hello())