Python

How to make a single list from multiple lists in Python

January 17, 2022

How to make a single list from multiple lists in Python

In this article we will learn how to make a single list from multiple lists in Python, that is, to condense several lists into one in a simple way.

single list from multiple lists cover

Hey you all programmers, how are you? Let’s learn more about lists in Python!

To achieve this goal we have some possibilities, in the first one we want to show you,  we will make a loop with another loop inside, and we will use the” for” statement

The first loop goes through all the lists, the second loop goes through each item in the lists and adds to the main list which will be our only

Let’s see an example:

a = [1,2,3,4]
b = [5,6,7,8]
c = [9,10]

listWithLists = [a,b,c]

myList = []

for l in listWithLists :
 for i in l:
  myList.append(i)

print(listaUnica)

This way the loop runs through lists a, b and c, and the loop inside each list appends the item to the singlelist

Another possibility is to use the itertools library

We will have the same result, but in fewer lines of code

See an example:

import itertools

a = [1,2,3,4]
b = [5,6,7,8]
c = [9,10]

listWithLists = [a,b,c]

myList = list(itertools.chain(*listWithLists))

print(myList)

The output of both options will be:

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

Another interesting way, however should be avoided in production because of the performance

It’s using Monoids, basically it adds the lists passed to the second argument which will be an empty list

See the example:

a = [1,2,3,4]
b = [5,6,7,8]
c = [9,10]

listWithLists = [a,b,c]

myList = sum(listWithLists, [])

print(myList)

In addition to the performance issue, this statement is very implicit.

That is, it does not follow the standards of Pythonic code, so it should be avoided and only learned out of curiosity!

you will see other points that the assert addresses

Conclusion

In this article we learned  how to make a single list from multiple lists

We use several approaches such as: for and for, itertools and a monoid

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x