How to Flatten in a Python List

Python program lists are one of the most notable features in Python. A list can function as both a data type and a container for instances of other nested data types. In fact, we can even have lists that contain lists. When a Python list contains multiple instances of other lists we consider it to be a multidimensional list, irregular list or a nested list. Some libraries, such as NumPy, add even more flexibility to multidimensional lists by adding similar structures such as a numpy array or other irregular list.

Multidimensional lists are extremely useful. However, we sometimes need to merge the contents together using a flatten function in a python program. This turns a nested list into a flat list. We have a few different approaches that we can use to flatten a flattening list of nested objects. Consider the following example of how to Python flatten list.

animals = [
["Deer", "Coypu", "Shrew", "Otter"],
["Kingfisher", "Woodpecker"],
["Salamander", "Snake", "Turtle"]
]
modAnimals = []
for sublist in animals:     
  for animal in sublist:
        modAnimals.append(animal)
print(modAnimals)

In this example we’re going about the data structure flattening process in a fairly straightforward manner. We aren’t using any special Python script function or recursive function method. Instead, we’re using an approach that simply works through a single list with a standard integer loop method.

We start out with a nested list of animals that focuses on mammals, birds, reptiles and amphibians. In this flattening list example, consider a case where we need to look at all animals as a whole without separating them by subtype. In order to do that we simply need to flatten the multiple list data structure.

We can accomplish this by creating a new single list called modAnimals to hold the nested data we’re working with. This will ensure that we still have an unmodified animals input list to refer back to if needed. Keep in mind that we could always simply assign the contents of modAnimals back to animals (the given list element) if desired.

The for loop goes through every entry in the animals given list and adds them to modAnimals. This essentially removes the multidimensional aspect of the initial animals list. This is all possible because lists are highly iterable and fit quite easily into loops.

Once the loop finishes we can print out the results and see that modAnimals contains the data from our original list element in a flattened state. This method is effective, but it’s not really leveraging Python in the most efficient way possible. Consider the next example of Python code to see a more Python focused approach to convert list manipulation.

animals = [
["Deer", "Coypu", "Shrew", "Otter"],
["Kingfisher", "Woodpecker"],
["Salamander", "Snake", "Turtle"]
]
animals = [animal for sublist in animals for animal in sublist]
print(animals)

In this example we’re using list comprehension to really leverage Python’s powerful list manipulation to work through a nested structure. List comprehension lets us essentially use some type of program logic within a list declaration. In this case the logic is performed as a for loop which assigns items from the animals list.

At the end of the process the results are assigned back into, and overwrite, the animals list. This essentially lets us flatten a list with a single line of code. Finally, at the final line, we print the animals variable to demonstrate that the list has been successfully flattened.

We can also accomplish this by using an intertools chain. Intertools is a part of the standard Python library, though we will need to import it first. Let’s take a look at how we can use an intertools chain flatten method to turn a nested list into a regular list.

import itertools
animals = [
["Deer", "Coypu", "Shrew", "Otter"],
["Kingfisher", "Woodpecker"],
["Salamander", "Snake", "Turtle"]
]
animals = list(itertools.chain(*animals))
print(animals)

In this example, we use the * parameter to unpack our list object and present it to intertool’s chain method. The chain essentially works through iterables. The end result is then passed to the list function. As the name suggests, the list function will convert the iterable created by chain into a list. We can then simply reassign that result to our animals variable. We then print it out to show that it is indeed a flattened list.

How to Flatten in a Python List

Leave a Reply

Your email address will not be published.

Scroll to top