en A guide to flattening lists and lists of lists in Python

A guide to flattening lists and lists of lists in Python

Converting a 2D array to a 1D array is called flattening . There are many approaches to solving the problem.

In this tutorial, we will consider some of them.

Let’s look at an example.

input

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

output

 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
A guide to flattening lists and lists of lists in Python
A guide to flattening lists and lists of lists in Python

#1.Loop

The most common way to solve the problem is to use loops. I think most people already have it. Let’s take a look at the steps to solve the problem using loops.

  • Initialize the list of lists with dummy data and name it data .
  • Next, initialize an empty list called flat_list .
  • Iterate over the data .
    • Unpacks all elements from the current list.
    • Add them to flat_list using list append method.
  • Print the results.

See the code in question below.

 # initializing the data and an empty list
data = [[1, 2, 3], [4, 5], [6, 7, 8, 9, 10]]
flat_list = []

# iterating over the data
for item in data:
    # appending elements to the flat_list
    flat_list += item

# printing the resultantn flat_list
print(flat_list)

You can use another loop instead of concatenation operator to add sublist elements to flat_list . You can also use list comprehensions instead of loops.

Both perform the same task. Let’s take a look at the next method to solve the problem.

A guide to flattening lists and lists of lists in Python
A guide to flattening lists and lists of lists in Python

#2. Itertools – Chain

We use a method called chain from the itertools built-in module.

The method chain iterates through each sublist and returns elements until there are no more sublists. Returns an iterable object that needs to be converted to a list.

Let’s take a look at the steps to resolve the issue.

  • Initialize the list of lists with dummy data and name it data .
  • Get a flattened iterable using itertools.chain(*data) .
  • Convert the resulting iterable to a list.
  • Print the flattened list.

Check the code in the snippet below.

 # importing the module
import itertools

# initializing the data
data = [[1, 2, 3], [4, 5], [6, 7, 8, 9, 10]]

# flattening the list and storing the result
flat_list = itertools.chain(*data)

# converting iterable to list and printing
print(list(flat_list)) 
A guide to flattening lists and lists of lists in Python
A guide to flattening lists and lists of lists in Python

#3.Flatten multi-level lists

We have seen how to flatten a list of lists. The methods described above to flatten a list do not work for multi-level lists. Let’s look at an example.

input

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

output

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

Since the depth of the list is not known before the program, we must use recursion to solve the problem.

  • Initialize the data as shown in the example and name it data .
  • Initialize an empty list called flat_list .
  • Create a function called flatten_list .
    • Iterates through the elements of the specified list.
    • If the element is a list, call the same function again recursively.
    • If the element is not a list, add it to flat_list .
  • Call the function by specifying data .
  • This function fills all the elements in the flat_list list.
  • Check the output by printing flat_list .

Huh! Many steps to create code. Don’t worry. It will take less than a few minutes to convert the above statement into code.

 # initializing the data and empty list
data = [1, [2, 3, [4, 5]], 6, [[7], [8, 9]]]
flat_list = []

# function
def flatten_list(data):
    # iterating over the data
    for element in data:
        # checking for list
        if type(element) == list:
            # calling the same function with current element as new argument
            flatten_list(element)
        else:
            flat_list.append(element)

# flattening the given list
flatten_list(data)

# printing the flat_list
print(flat_list)

Note that we are not converting existing lists. Instead, it created a new list using the specified list elements.

A guide to flattening lists and lists of lists in Python
A guide to flattening lists and lists of lists in Python

conclusion

I hope you enjoyed the tutorial. There may be many other ways to flatten a list in Python, but I think the above method is probably the easiest.

Have fun coding 🙂

A guide to flattening lists and lists of lists in Python
A guide to flattening lists and lists of lists in Python