List Comprehensions
List comprehensions provide a concise way to create lists. This can replace the need for using loops to generate lists.
squares = [x**2 for x in range(10)]
Generator Expressions
Similar to list comprehensions but with parentheses, generator expressions are used for creating generators. These are memory-efficient and suitable for large data sets.
squares_gen = (x**2 for x in range(10))
Default Dictionary
The defaultdict from the collections module is a dictionary-like class that provides default values for missing keys.
from collections import defaultdict
dd = defaultdict(int)
dd['key'] += 1
Named Tuples
namedtuple creates tuple subclasses with named fields. This makes code more readable by accessing fields by name instead of position.
from collections import namedtuple
Point = namedtuple('Point', 'x y')
p = Point(10, 20)
Enumerate Function
The enumerate function adds a counter to an iterable and returns it as an enumerate object. This is useful for obtaining both the index and the value in a loop.
for index, value in enumerate(['a', 'b', 'c']):
print(index, value)
Zip Function
The zip function combines multiple iterables into a single iterable of tuples. This is useful for iterating over multiple sequences simultaneously.
names = ['a', 'b', 'c']
ages = [20, 25, 30]
combined = list(zip(names, ages))
Set Comprehensions
Similar to list comprehensions, set comprehensions create sets in a concise way.
unique_squares = {x**2 for x in range(10)}
Frozenset
A frozenset is an immutable set. It's useful when you need a set that cannot be changed after creation.
fs = frozenset([1, 2, 3, 2, 1])
Counter
The Counter class from the collections module counts the occurrences of elements in a collection. It's useful for counting hashable objects.
from collections import Counter
counts = Counter(['a', 'b', 'c', 'a', 'b', 'b'])
Context Managers
Using the with statement, context managers handle resource management, like file I/O, efficiently and cleanly.
with open('file.txt', 'r') as file:
contents = file.read()
dataclass
The dataclass decorator simplifies class creation by automatically adding special methods like init and repr.
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
Decorators
Decorators are functions that modify the behavior of other functions. They are useful for logging, access control, memoization, and more.
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
Asyncio
The asyncio module provides a framework for asynchronous programming. This is useful for I/O-bound and high-level structured network code.
import asyncio
async def main():
print('Hello')
await asyncio.sleep(1)
print('World')
asyncio.run(main())
0 Comments:
Post a Comment