List Comprehension

Nested List Comprehension

# Make a list with repetition
print([x for i in range(3) for x in (1, 2)])
# [1, 2, 1, 2, 1, 2]
 
# Equivalent
l = []
x for i in range(3):
     for x in (1, 2):
        l.append(x)
print(x)
 
# Flatten 2d list
nested_list = [[1, 2], [3, 4], [5, 6]]
print([e for sub_list in nested_list for e in sub_list])
# [1, 2, 3, 4, 5, 6]
 
# Equivalent
l = []
for sub_list in nested_list:
    for e in sub_list:
        l.append(e)
print(e)

List Comprehension with If Else

print(['e' if e%2==0 else 'o' for e in range(1, 10)])
# ['o', 'e', 'o', 'e', 'o', 'e', 'o', 'e', 'o']
 
# Equivalent
l = []
for e in range(1, 10):
    x = 'e' if e%2==0 else 'o'
    l.append(x)
print(l)

f-string

var = "value"  
print(f"{var=}")
# var='value'
 
print(f"{1+2=}")
# 1+2=3

Pattern Matching (match case)

num = 1
match num:
    case 1:
        print("one")
    case 2:
        print("two")
    case 3:
        print("three")
    case _:
        print("other")
 
one

Walrus operator

Examples

text = "Hello, world!"
if (n := len(text)) > 5:
    print(f"The text '{text}' has {n} characters, which is more than 5.")
else:
    print(f"The text '{text}' is short with {n} characters.")
while (user_input := input("Enter a number or 'quit': ")) != 'quit':
    try:
        number = int(user_input)
        print(f"You entered: {number}")
    except ValueError:
        print("Invalid input. Please enter a number.")
print("Exiting")
numbers = [10, 5, 22, 3, 18, 7, 14]
filtered_and_squared = [(sq := x**2) for x in numbers if sq > 50]  
print(filtered_and_squared)  # Output: [100, 484, 324, 196]

Performance Optimization

Pickle

Library for saving and loading python instance to a file.

Object I/O

# dump to file
with open("object.pkl", "wb") as f:
    pickle.dump(object, f)
 
# load from file
with open("object.pkl", "rb") as f:
    object = pickle.load(f)

Binary I/O

# dump to bytes object
bytes = pickle.dumps(object)
 
# load from bytes object
object = pickle.loads(bytes)

pathlib

from pathlib import Path
 
path = pathlib.Path.cwd() / "file.txt"
 
file = path.read_text()
path.write_text("write something")