fbpx

How To Make A Flat List Out Of A List Of Lists

Are you wondering how to make a flat list out of a list of lists? Do you want to save the ordered collection of various items of 2-D into the 1-D list in Python?

If yes! Then this is the best guide to learn how to make a flat list out of a list of lists. But before that, we want to make beginners familiar with the list in Python.

The list is one of the built-in data structures that is available among the dictionaries, sets, and tuples in Python. It is used to save similar or different types of ordered items. The square brackets and commas are used to make a list.

For example: Changing the [[1,2],[3,4]] to [1,2,3,4].

Is there any benefit of using the list in Python?

Yes, there is!!

We have mentioned that a list is one of Python’s data structures that is changeable, mutable, or has an ordered sequence of various components. The list allows you to keep all the relevant data collectively. 

This data may belong or not belong to a similar data type. But the user can perform the operations and techniques over each element of the list simultaneously. That is why there is a benefit of using the list in Python programs. 

Bonus: Is it also possible to know how many elements are there in the list? Yes, it is possible to know by using the len() function.

Example: 
list = [“p”, “q”, “r”, “s”, “t”]print(len(list))

Output:
5

What is a flattening list, and why do we need it?

We know that a list of lists is taken as 2 -D arrays in Python. However, Python does not hold the array concept as that of Java or C. Therefore, flattening the list of lists makes the components of sublists in the 1-D array. 

For instance: [[a,b,c],[d,e,f] -> [a,b,c,d,e,f].

Python users need these flattening lists to perform a similar operation on each element of the list simultaneously. A flattening list can be created with different methods. We have listed all the useful methods for it.

Different approaches for how to make a flat list out of a list of lists

Before proceeding to the flat list, let’s begin with a simple example: change [[1,2],[3,4]] to [1,2,3,4].

This kind of flattening is termed shallow flattening because it can falt the list to 1-D depth.

Output

[1, 2, 3, 4]

This is how to make a flat list out of a list of lists. Now, let’s move to the different approaches to make the flat list.

1. Nested loop

When a loop (either while loop or for-loop) involves other loops in the main body block, then we can take it as a nested loop. 

Output

(‘Previous List:’, [[0, 1, 2], [3, 4, 5], [6, 7, 8]])

Output

(‘Flattened List:’, [0, 1, 2, 3, 4, 5, 6, 7, 8])

2. Functools (reduce-iconcat) [Using Python Library]

If you want to execute the programs much faster, this approach is the best approach. Although it does not have any automatic system that can be work quickly, the user needs to import it along with few libraries.

Output

(‘Previous List:’, [[0, 1, 2], [6, 7, 8], [3, 4, 5]])

Output

(‘Flattened List:’, [0, 1, 2, 6, 7, 8, 3, 4, 5])

3. Itertools(chain) [Using Python Library]

It is a module that has various functions. These functions are used for managing iterators. These modules make iterating using the iterables such as string and list easily.

It is another approach for how to make a flat list out of a list of lists in Python. Itertools are not as fast as the functools, but it is quite better than nested-loop.

Output

(‘Previous List:’, [[0, 1, 2], [6, 7, 8], [3, 4, 5]])

Output

(‘Flattened List:’, [0, 1, 2, 6, 7, 8, 3, 4, 5])

4. Sum [Using built-in function]

Summing the 2-D list into 1-D is another best method to flatten the list. Sum function has two factors: iterable and start.

[iterable: a list of list and start: an empty list in which we will add the sublist.]

It is quite slow as compared to the chain() and itertools() function. But it is always convenient as the user does not need to import anything.

Output

(‘Previous List:’, [[0, 1, 2], [6, 7, 8], [3, 4, 5]])

Output

(‘Flattened List:’, [0, 1, 2, 6, 7, 8, 3, 4, 5])

5. Lambda [Using built-in function]

The lambda does not mean to change the items in the list. Rather, it can use for sorting the elements. Here, we have not only changed the list in flatten list but also sorted the list in a well-structured manner.

Output

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

Apart from these, there are various methods regarding how to make a flat list out of lists, such as:

  • Functools – reduce
  • NumPy – concatenate
  • NumPy – flat
  • List Comprehension

A python user can use any of these to carry out the Python operations simultaneously over the entire list.

Conclusion

To implement the Python operations with ease, the listing is the best method. Changing the 2-D list to a 1-D list is known as flattening. There are various approaches to do this, and we have listed all the relevant methods.

Hope you understand things. Still, have an issue with the flattening list? Don’t worry! Comment your query in the below comment section, and we will help you in the best possible way. We always try our best to help you to enhance the Python skills. 

Answer The Following Multiple Asked Questions To Test Your Knowledge

  1. Suppose list1 is [“1”, “2”, “3”], what is len(list1)?

a) 4

b) 3

c) Error

d) None

Correct Answer: (b), as there are three components in the list; therefore, the length of the list is 3.
  1. What is the output of the following code?

list1 = [“abc”, 34, True, 40, “male”]

print (list1)

(a) Error

(b) Not defined

(c) [“abc”, 34, True, 40, “male”]

(d) [‘abc’, 34, True, 40, ‘male’]

Correct Answer: (d) The above code can print heterogeneous elements of the list.
  1. Is it possible to add an element to the list using append?

(a) True

(b) False

Correct Answer: (a) Yes, it is possible to add an element to the list using append. Execute the following code to test it:
x = [‘a’,’b’,’c’]x.append(‘d’)print(x)
Output:
[‘a’, ‘b’, ‘c’, ‘d’]
  1. What is the output of the following code?

i = [ [0,1],  [ 2 ], [ 3, 4 ] ]

flatten_list = [item for subi in i for item in subi]

print(flatten_list)

(a) [0, 1, 2, 3, 4]

(b) [0 1 2 3 4]

(c) [‘0’ ‘1’ ‘2’ ‘3’ ‘4’]

(d) Error

Correct Answer: (a) Implement the code to check the output.
  1. The output of the following code is:

one = [‘a’, ‘b’, ‘c’]

two = [‘1’, ‘2’, ‘3’]

list = one + two 

print(list)

(a) Error

(b) None

(c) []

(d) [‘a’, ‘b’, ‘c’, ‘1’, ‘2’, ‘3’]

Correct Answer: (d) Execute the program to check the output.

Archana

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top