🔥 Python Tip: itertools — Powerful Iteration Tools
The itertools module gives you super-powered loops without writing complex code.
Chain — Combine Iterables
from itertools import chain
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
for num in chain(list1, list2, list3):
print(num, end=' ') # 1 2 3 4 5 6 7 8 9Product — All Combinations
from itertools import product
colors = ['red', 'blue']
sizes = ['S', 'M', 'L']
for color, size in product(colors, sizes):
print(f"{color}-{size}", end=' ')
# red-S red-M red-L blue-S blue-M blue-LGroupby — Group Consecutive Items
from itertools import groupby
data = sorted([
('A', 1), ('B', 2), ('A', 3), ('B', 4)
])
for key, group in groupby(data, key=lambda x: x[0]):
print(f"{key}: {list(group)}")
# A: [('A', 1), ('A', 3)]
# B: [('B', 2), ('B', 4)]Islice — Slice Any Iterable
from itertools import islice
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
# Get first 10 Fibonacci numbers
first_10 = list(islice(fibonacci(), 10))
print(first_10) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]💡 itertools is memory-efficient because it works with generators — perfect for processing large datasets!
