Flattening Lists in Python: 5 Essential Methods

The Power of List Comprehension

When it comes to flattening lists in Python, there’s no shortage of approaches. But some methods stand out for their elegance and efficiency. Take, for instance, the humble list comprehension. This Pythonic technique allows you to access each element of a sublist and store it in a new list, all in a single line of code.

Example 1: Unleashing the Power of List Comprehension


my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_list = [num for sublist in my_list for num in sublist]
print(flat_list) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

The Traditional Approach: Nested for Loops

Of course, not everyone may be familiar with list comprehensions. No worries! A more traditional approach involves using nested for loops to iterate over each sublist and its elements.

Example 2: The Non-Pythonic Way


my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_list = []
for sublist in my_list:
for num in sublist:
flat_list.append(num)
print(flat_list) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Leveraging the itertools Package

For those who prefer a more functional approach, the itertools package offers a convenient solution. The chain() method returns each element of each iterable (i.e., sublist), which can then be converted into a list using the list() function.

Example 3: The itertools Way


import itertools
my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_list = list(itertools.chain(*my_list))
print(flat_list) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

The sum() Method: A Surprisingly Effective Solution

Believe it or not, the humble sum() method can also be used to flatten lists. By providing two arguments – my_list and an empty list – sum() combines them to produce a flattened list.

Example 4: The sum() Solution


my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_list = sum(my_list, [])
print(flat_list) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

The Lambda and reduce() Approach

Last but not least, we have the lambda and reduce() method combination. This approach applies a lambda function to all elements of my_list, effectively flattening the list.

Example 5: The Lambda and reduce() Solution


import functools
my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_list = functools.reduce(lambda x, y: x + y, my_list)
print(flat_list) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Leave a Reply

Your email address will not be published. Required fields are marked *