Modern Python Features & Functions (Cheat Sheet)
1. f-Strings (Formatted Strings)
Old way:
name = "Alice"
print("Hello " + name + "!")
Modern:
name = "Alice"
print(f"Hello {name}!") # f-strings are easier and faster.
2. Type Hinting
Old way:
def add(x, y):
return x + y
Modern:
def add(x: int, y: int) -> int:
return x + y # Improves readability and editor support.
3. Walrus Operator (:=)
Old way:
value = input("Enter: ")
while value != "exit":
print(value)
value = input("Enter: ")
Modern:
while (value := input("Enter: ")) != "exit":
print(value) # Assign and compare in one line.
4. Enumerate and Zip
enumerate:
for i, item in enumerate(["a", "b", "c"]):
print(i, item)
zip:
names = ["Alice", "Bob"]
scores = [90, 85]
for name, score in zip(names, scores):
print(f"{name}: {score}")
5. List Comprehensions
Old way:
squares = []
for i in range(10):
[Link](i*i)
Modern:
squares = [i*i for i in range(10)] # One-liner, cleaner
6. Dictionary Comprehensions
squares = {i: i*i for i in range(5)} # Same idea as list comp
7. Set Comprehensions
unique = {char for char in "banana"} # {'b', 'a', 'n'}
8. Unpacking with * and **
def add(a, b, c):
return a + b + c
nums = [1, 2, 3]
print(add(*nums)) # Unpacks list into function args
data = {"a": 1, "b": 2, "c": 3}
print(add(**data)) # Unpacks dict into args
9. Pathlib (Modern File Paths)
from pathlib import Path
file = Path("[Link]")
if [Link]():
print(file.read_text())
10. Context Managers (with statement)
with open("[Link]") as f:
data = [Link]()
# Automatically closes the file