Post thumbnail
PROGRAMMING LANGUAGES

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

By Archana

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].

Table of contents


  1. Is there any benefit of using the list in Python?
  2. What is a flattening list, and why do we need it?
  3. Different approaches for how to make a flat list out of a list of lists
    • Nested loop
    • Functools (reduce-iconcat) [Using Python Library]
    • Itertools(chain) [Using Python Library]
    • Sum [Using built-in function]
    • Lambda [Using built-in function]
  4. Conclusion
  5. Answer The Following Multiple Asked Questions To Test Your Knowledge

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. 

Before diving into the next section, ensure you’re solid on Python essentials from basics to advanced level. If you are looking for a detailed Python career program, you can join GUVI’s Python Career Program with placement assistance. You will be able to master the Multiple Exceptions, classes, OOPS concepts, dictionary, and many more, and build real-life projects. Also, if you would like to explore Python through a Self-paced course, try GUVI’s Python Self-Paced course.

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.

pxpDIYR 7REb0BSVcxtAEbuT vlAy9zqkAl8 8erH YjnoWolrmPhBuHQS7OGz7npiq64NxD jFbBkFHPUEDQ sUT bqZkTLmrMsIH006 p50lritiCfWw8QWa0ocWcKHEV4gQY

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.

MDN

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. 

3YOoqPQ3gjKswjlH1kXa10hb4HxCW6x0TGm0list1mgh97MjaolFtQLr0u4UMrDk74HJNVrrRj5KAJOYHDGkBsD NJmWtXOrhxAj Bex0rcne EANJ7cj21s7MvV adk0l8ZDw

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.

aH3sNy2eu7DO1AlhZNLGpTq1JeHf4pzh3FzIewMmCuR5NU mIPy1PiB52 FO0YC2TDMuaSRx98a7JWGO6WLAJfV38AzrYa0VmPthiHnINR 9qoflBqsOpNjEMnHL28PdL8V3pw0

Output

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

5I 5QkBuCqX57fbI iE rwClH1v 9u8G4aY1QsEHfoqZnkHpZNKPD7lFXpCKV9 yX9CQ3f6sNlTx3Idpz jSEQiU Qbd0rL9tfrcXq n6RjMMIIt5ScVTnhGyQDHIE9DO8OZo

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.

CxLLXW85qhlyXrQIR9TrlBuuBOkJ x8zS79qJcSpGPi0X8DIVpBn4glTomPt BK693QPlWDnW5tXLMvHfqaOxZWzb3jfDt0Z15zRm3cTMNfi585pv9pmnFqnRG74PG9 I3YA n8

Output

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

6Vzop4ZSf765FsGzcjVwOgdtKkpxQKzQof9CqxatFceigkKQ OpGtEFEQjvz5p6cSMI6Xic vjkmGajY9KD in sO3O1uu 3d5OHNCpuAPqbnYt7D 9sgajlV7EYT76a9AshoHU

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.

ZN5cPZKQ2n4Z9veSxmZVS20Vh q p3I1XUcBd YlUoU6rRNJAPYRuPe86pg4WbfF7L0vJ8DThjsswF8nYZPrvIFkDiQLb4k1cKQWmuAwHDNtbk3i8DHnv FBDYuiMCljfBYbYM

Output

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

0Vq66ANa FRgJ42eoMy6kdcefNkwaJzxi

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.

gemeN2ORKhzmeN4Wgq6ByOQgOvczNbxwhQC2ZdYOOS1qG4wx2I sgLuGM23SxMffk9JGgz419ynm7

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.

Kickstart your Programming journey by enrolling in GUVI’s Python Career Program where you will master technologies like multiple exceptions, classes, OOPS concepts, dictionaries, and many more, and build real-life projects. Alternatively, if you would like to explore Python through a Self-Paced course, try GUVI’s Python Self-Paced course.

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 your Python skills

MDN

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.

Career transition

Did you enjoy this article?

Schedule 1:1 free counselling

Similar Articles

Loading...
Share logo Copy link
Free Webinar
Free Webinar Icon
Free Webinar
Get the latest notifications! 🔔
close
Table of contents Table of contents
Table of contents Articles
Close button

  1. Is there any benefit of using the list in Python?
  2. What is a flattening list, and why do we need it?
  3. Different approaches for how to make a flat list out of a list of lists
    • Nested loop
    • Functools (reduce-iconcat) [Using Python Library]
    • Itertools(chain) [Using Python Library]
    • Sum [Using built-in function]
    • Lambda [Using built-in function]
  4. Conclusion
  5. Answer The Following Multiple Asked Questions To Test Your Knowledge