Skip to content

Unpack list of lists Python

  • by

In Python, you can unpack a list of lists using a combination of list unpacking and list comprehensions. List unpacking allows you to extract the elements from nested lists into a single flat list. Here’s how you can do it:

Let’s say you have a list of lists like this:

list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

To unpack this list of lists into a single flat list, you can use a list comprehension along with the for loop:

flat_list = [item for sublist in list_of_lists for item in sublist]
  1. We use a list comprehension to iterate over each sublist in the list_of_lists.
  2. For each sublist, we use another loop to iterate over each item in the sublist.
  3. The item is added to the flat_list for each iteration, resulting in a single flat list.

After running the above code, the flat_list will be [1, 2, 3, 4, 5, 6, 7, 8, 9].

Now, if you have a list of lists with different lengths, the same approach will work and it will flatten the list of lists:

list_of_lists = [[1, 2], [3, 4, 5], [6], [7, 8, 9, 10]]
flat_list = [item for sublist in list_of_lists for item in sublist]

After running this code, the flat_list will be [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].

Unpack a list of lists Python example

Here’s a step-by-step example of unpacking a list of lists in Python:

# Define a list of lists
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Create an empty list to store the unpacked elements
flat_list = []

# Using nested loops, unpack the elements from the list of lists
for sublist in list_of_lists:
    for item in sublist:
        flat_list.append(item)

# Display the result
print(flat_list)

Output:

Unpack list of lists Python

How do I make a flat list out of a list of lists?

Answer: To flatten a list of lists and convert it into a single flat list, you can use various methods in Python. Here are some common approaches:

Using List Comprehension:

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

Using itertools.chain.from_iterable:

import itertools

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

Using sum() function with an empty list:

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

These methods work by iterating through each sublist and appending its elements to the flat_list. You can choose any of these methods based on your preference and coding style. The first method using list comprehension is the most common and is considered Pythonic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading