Quick Python Tip: itertools.chain Flattens Lists Without Nested Loops
When working with multiple lists in Python, you often need to flatten them into a single list. A common approach is to use nested loops, but this can be cumbersome and inefficient. For example, consider the following code that uses nested loops to flatten two lists:
list1 = [[1, 2], [3, 4]]
list2 = [[5, 6], [7, 8]]
flattened_list = []
for sublist in list1 + list2:
for item in sublist:
flattened_list.append(item)
print(flattened_list) # [1, 2, 3, 4, 5, 6, 7, 8]
However, there's a more elegant and efficient way to achieve this using itertools.chain. You can pass multiple lists to itertools.chain using the * operator, which unpacks the lists into separate arguments. Here's an example:
import itertools
list1 = [[1, 2], [3, 4]]
list2 = [[5, 6], [7, 8]]
flattened_list = list(itertools.chain(*list1 + list2))
print(flattened_list) # [1, 2, 3, 4, 5, 6, 7, 8]
The itertools.chain approach is not only more concise but also more memory-efficient, as it avoids creating intermediate lists.
The takeaway is that using itertools.chain(*lists) is a more efficient and Pythonic way to flatten multiple lists than using nested loops.
Follow me on Dev.to for daily Python tips and quick guides!
💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $29.99*
💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $29.99*
💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $29.99*
Top comments (0)