Combining Streams: `itertools.chain` & `zip_longest`
`itertools.chain(a, b)` glues separate iterables into one seamless stream 🔗. `zip_longest` pairs items without truncating the longer list 🗂️.
import itertools
# Seamless concatenation:
combined = list(itertools.chain([1, 2], [3, 4]))
print(combined) # [1, 2, 3, 4] 🔗
# Pairing with fallback:
pairs = list(itertools.zip_longest(["a", "b"], [1], fillvalue="?"))
print(pairs) # [('a', 1), ('b', '?')] 🧩
# 23. Combining Streams: `itertools.chain` & `zip_longest` `itertools.chain(a, b)` glues separate iterables into one seamless stream 🔗. `zip_longest` pairs items without truncating the longer list 🗂️: ```python import itertools # Seamless concatenation: combined = list(itertools.chain([1, 2], [3, 4])) print(combined) # [1, 2, 3, 4] 🔗 # Pairing with fallback: pairs = list(itertools.zip_longest(["a", "b"], [1], fillvalue="?")) print(pairs) # [('a', 1), ('b', '?')] 🧩 ``` Standard `zip()` silently drops elements when one list is shorter than the other. `zip_longest` protects against silent data loss by substituting a fallback placeholder. 🛡️ --- ### Question How does `itertools.chain([1], [2])` differ from `[1] + [2]`? ⚡ - [ ] a. `chain` streams elements lazily without copying memory into a new allocated list - [ ] b. `chain` reverses the order of elements - [ ] c. `[1] + [2]` requires downloading extra packages from PyPI 📦 - [ ] d. `chain` only works on even numbers on alternate days 📅 --- ### Challenge Chain two lists `[10, 20]` and `[30, 40]` using `itertools.chain`. Convert to `list()` and print it. 🎯 <details> <summary>Solution</summary> ```python import itertools res = list(itertools.chain([10, 20], [30, 40])) print(res) ``` </details>