Wednesday, January 22, 2025
HomeProgrammingHow Do I Make a Flat List Out of a List of...

How Do I Make a Flat List Out of a List of Lists? – Python

To create a flat list from a list of lists in Python, you can use several approaches. Here are the most common methods:

1. Using List Comprehension

List comprehension is a concise and Pythonic way to flatten a list of lists.

nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]
flat_list = [item for sublist in nested_list for item in sublist]
print(flat_list)

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

2. Using the itertools.chain Function

The itertools.chain function is efficient and widely used for flattening lists.

from itertools import chain

nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]
flat_list = list(chain.from_iterable(nested_list))
print(flat_list)

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

3. Using a Nested Loop

A simple, straightforward way is to use nested for loops.

nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]
flat_list = []

for sublist in nested_list:
    for item in sublist:
        flat_list.append(item)

print(flat_list)

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

4. Using NumPy’s flatten (For Numeric Data)

If you are working with numeric data, you can use NumPy for flattening.

import numpy as np

nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]
flat_list = np.array(nested_list).flatten().tolist()
print(flat_list)

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

5. Using Recursion (For Deeply Nested Lists)

If you have a list with arbitrary nesting levels, recursion can flatten it.

def flatten(nested_list):
    flat_list = []
    for item in nested_list:
        if isinstance(item, list):
            flat_list.extend(flatten(item))
        else:
            flat_list.append(item)
    return flat_list

nested_list = [[1, [2, 3]], [4, 5], [6, [7, 8]]]
flat_list = flatten(nested_list)
print(flat_list)

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

6. Using the sum() Function (For Simple Nested Lists)

The sum() function can be used creatively to flatten a list of lists, but it is less efficient.

nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]
flat_list = sum(nested_list, [])
print(flat_list)

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

Which Method Should You Use?

  • For Performance: Use itertools.chain.
  • For Readability: Use list comprehension.
  • For Arbitrary Nesting: Use recursion.
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x