“`python
# 1. List Comprehension for concise list creation/transformation
# Create a list of squares for numbers 0 to 4
squares = [x**2 for x in range(5)]
print(f”Squares: {squares}”) # Output: Squares: [0, 1, 4, 9, 16]
# Filter even numbers from an existing list
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [num for num in numbers if num % 2 == 0]
print(f”Even numbers: {even_numbers}”) # Output: Even numbers: [2, 4, 6]
# 2. Dictionary Comprehension for concise dictionary creation/transformation
# Create a dictionary mapping numbers to their squares
square_dict = {x: x**2 for x in range(3)}
print(f”Square dictionary: {square_dict}”) # Output: Square dictionary: {0: 0, 1: 1, 2: 4}
# 3. F-Strings for easy string formatting (Python 3.6+)
name = “Alice”
age = 30
message = f”Hello, {name}! You are {age} years old.”
print(message) # Output: Hello, Alice! You are 30 years old.
# Include expressions directly
result = f”The sum of 5 and 3 is {5 + 3}.”
print(result) # Output: The sum of 5 and 3 is 8.
# 4. Enumerate for iterating with index
# Iterate over a list and get both index and value
fruits = [“apple”, “banana”, “cherry”]
for index, fruit in enumerate(fruits):
print(f”{index}: {fruit}”)
# Output:
# 0: apple
# 1: banana
# 2: cherry
# 5. Zip for combining multiple iterables
# Combine two lists element-wise
names = [“Alice”, “Bob”]
scores = [95, 88]
for name, score in zip(names, scores):
print(f”{name} scored {score}”)
# Output:
# Alice scored 95
# Bob scored 88
# 6. Default Dictionary for handling missing keys gracefully
from collections import defaultdict
# Count occurrences of elements in a list
data = [‘a’, ‘b’, ‘a’, ‘c’, ‘b’, ‘a’]
counts = defaultdict(int) # Default value for missing keys is 0
for item in data:
counts[item] += 1
print(f”Counts: {dict(counts)}”) # Output: Counts: {‘a’: 3, ‘b’: 2, ‘c’: 1}
# 7. Context Managers (with statement) for resource management
# Automatically close files or release resources
file_path = “example.txt”
with open(file_path, “w”) as f:
f.write(“Hello, world!\n”)
f.write(“Python is great.”)
# File is automatically closed after exiting the ‘with’ block
with open(file_path, “r”) as f:
content = f.read()
print(f”File content:\n{content}”)
# Output:
# File content:
# Hello, world!
# Python is great.
# 8. Function Arguments: *args and **kwargs
# *args for arbitrary number of positional arguments
def sum_all(*args):
total = 0
for num in args:
total += num
return total
print(f”Sum of 1, 2, 3: {sum_all(1, 2, 3)}”) # Output: Sum of 1, 2, 3: 6
# **kwargs for arbitrary number of keyword arguments
def print_info(**kwargs):
for key, value in kwargs.items():
print(f”{key}: {value}”)
print_info(name=”Charlie”, age=25, city=”New York”)
# Output:
# name: Charlie
# age: 25
# city: New York
# 9. Decorators for modifying functions/methods
# A simple decorator to log function calls
def logger(func):
def wrapper(*args, **kwargs):
print(f”Calling function {func.__name__} with args: {args}, kwargs: {kwargs}”)
result = func(*args, **kwargs)
print(f”Function {func.__name__} returned: {result}”)
return result
return wrapper
@logger
def add(a, b):
return a + b
add(10, 20)
# Output:
# Calling function add with args: (10, 20), kwargs: {}
# Function add returned: 30
# 10. `requests` library for HTTP requests
import requests
try:
response = requests.get(“https://jsonplaceholder.typicode.com/todos/1″)
response.raise_for_status() # Raises HTTPError for bad responses (4xx or 5xx)
todo = response.json() # Parse JSON response
print(f”\nFetched TODO item: {todo}”)
print(f”Title: {todo[‘title’]}”)
except requests.exceptions.RequestException as e:
print(f”Error fetching data: {e}”)
# Output (example):
# Fetched TODO item: {‘userId’: 1, ‘id’: 1, ‘title’: ‘delectus aut autem’, ‘completed’: False}
# Title: delectus aut autem
“`