You might often want to Flatten a list of lists or convert a list of lists into a single or tuple. For eg., you might want to convert entries [[1,2,3,4],[5],[6,7],[8,9,10],[11]] into [1,2,3,4,5,6,7,8,9,10,11]. So how do we do that?
Like C++ or Java, Python doesn’t support arrays. However, it does support dynamic-sized arrays known as lists. A list is a collection of heterogenous items stored in a single variable enclosed in square brackets. A list can be multi-dimensional or it can be cascaded into one another too.
Here are the top 5 methods that work best:
1. Flatten a list of lists using List Comprehension
List comprehension provides a shorter syntax to create or modify lists. It is a single-line tool that can be used in many situations considering lists.
For eg., consider a list my_list = [1,2,3,4]. A simple way to create this list is to manually assign it to a variable as,
my_list = [1,2,3,4]
Using list comprehension, we can create the same list as,
my_list = [i for i in range(1,5)]
print(my_list)
#Output
[1,2,3,4]
This is how the list comprehension works. It becomes super easy when the complexity of lists increases.
How to flatten out a list using list comprehension?
nested_list = [[1,2,3,4],[5],[6,7],[8,9,10],[11]]
flatten_list = [element for each_list in nested_list for element in each_list]
print(flatten_list)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Note:
Here, if the single element is present as an individual literal and not as a list, the code will throw a type error as it will not be considered as a list. Check this:
nested_list = [[1,2,3,4],5,[6,7],[8,9,10],11]
flatten_list = [element for each_list in nested_list for element in each_list]
print(flatten_list)
Output:
Traceback (most recent call last):
File "<string>", line 3, in <module>
File "<string>", line 3, in <listcomp>
TypeError: 'int' object is not iterable
2. Flatten a list of lists using Nested for loop:
An easy and naive approach to this problem is the for loop.
nested_list = [[1,2,3,4],[5],[6,7],[8,9,10],[11]]
flatten_list = list()
for each_list in nested_list:
for element in each_list:
flatten_list.append(element)
print(flatten_list)
Output:
[1,2,3,4,5,6,7,8,9,10,11]
3. Flatten a list of lists using reduce()
reduce() as the name suggests, basically reduces the iterable to something. It takes two parameters: a function that defines how the reduction has to be performed and an iterable.
The function can be imported from the functools module.
Here’s how we can flatten out the list using reduce():
from functools import reduce
nested_list = [[1,2,3,4],[5],[6,7],[8,9,10],[11]]
flatten_list = reduce(lambda a,b: a+b, nested_list)
print(flatten_list)
Output:
[1,2,3,4,5,6,7,8,9,10,11]
Here, the lambda (anonymous) function is used to concatenate the elements of the list.
4. Flatten a list of lists using itertools.chain()
itertools is a module in Python that provides functions that work on iterators to produce complex iterators. itertools is used to iterate over data structures that can be stepped over using a for-loop. It comes with Python as built-in and doesn’t require to install manually.
itertools.chain():
This function takes a series of iterables as input and groups all these inputted iterables together, returning a single iterable as output. The output is however gives the iterable and thus needs to convert into the list explicitly.
import itertools
nested_list = [[1,2,3,4],[5],[6,7],[8,9,10],[11]]
flatten_list= list(itertools.chain(*nested_list))
print(flatten_list)
Output:
[1,2,3,4,5,6,7,8,9,10,11]
5. Flattening a list of lists using flatten() from iteration_utitlies
iteration_utilites is a Python module that utilizes iterators and generators. It is based on the itertools module.
To install the module, type in the following command in your terminal:
pip install iteration_utitlies
flatten(): The function takes iterable as input and it flattens it with the first level of nesting. The output is a generator that is needed to convert to the list explicitly.
from iteration_utilities import flatten
nested_list = [[1,2,3,4],[5],[6,7],[8,9,10],[11]]
flatten_list = list(flatten(nested_list))
print(flatten_list)
Output:
[1,2,3,4,5,6,7,8,9,10,11]
Note: If you want to flatten a list of lists of lists, you can use deepflatten() function from the same module, which takes iterable and depth as input. The depth denotes how many levels of nesting need to be flattened.
This is how you can flatten a list of lists. But, the ways don’t limit up to 5 only. There are several others like numpy methods, extend, and various functions from functools, itertools, sum, etc. But these were the 5 methods that are frequently used. Hope this helps!
Thank you for visiting our website.
Also read:
- Python | Asking the user for input until they give a valid response
- Python | How to iterate through two lists in parallel?
- Python | How to sort a dictionary by value?
- Python | Remove items from a list while iterating
- Python | How to get dictionary keys as a list
- How to represent Enum in Python?
- 5 methods | Flatten a list of lists | Convert nested list into a single list in Python
- What does if __name__ == __main__ do in Python?
- Python | CRUD operations in MongoDB
- Create your own ChatGPT with Python
- Filter List in Python | 10 methods
- Radha Krishna using Python Turtle
- Yield Keyword in Python
- Python Programming Examples | Fundamental Programs in Python
- Python | Delete object of a class
- Python | Modify properties of objects
- Python classmethod
- Python | Create a class that takes 2 parameters, print both parameters
- Python | Create a class, create an object of the class, access, and print property value
- Python | Calculator using lambda
- Python | Multiply numbers using lambda
- Python | Print Namaste using lambda
- Iterate over a string in Python
- Python | join() | Join list of strings
- Python | isalnum() method | check if a string consists only of alphabetical characters or numerical digits
- Python | isupper() and islower() methods to check if a string is in all uppercase or lowercase letters
- Python | count substring in a String | count() method
- Python | enumerate() on String | Get index and element
- Python | Convert a String to list using list() method
- Euler’s Number in Python