Join of lists in Python

Asked

Viewed 162 times

0

How to join two lists in Python to form a single list ? For example, I have this list [[1, 0, 0, 0], [1, 1, 1, 0], [1, 0, 0, 0]] and I want to join her with [[1, 0, 1, 0], [1, 0, 1, 1]].

I want the result of this junction to be the following list:

[[1, 0, 0, 0], [1, 1, 1, 0], [1, 0, 0, 0], [1, 0, 1, 0], [1, 0, 1, 1]]

But he’s getting that way:

[[1, 0, 0, 0], [1, 1, 1, 0], [1, 0, 0, 0], [[1, 0, 1, 0], [1, 0, 1, 1]]

2 answers

4

Just use the method extend to merge a list with another. See the example below:

lista1 = [[1, 0, 0, 0], [1, 1, 1, 0], [1, 0, 0, 0]]
lista2 = [[1, 0, 1, 0], [1, 0, 1, 1]]

lista1.extend(lista2)
print(lista) # [[1, 0, 0, 0], [1, 1, 1, 0], [1, 0, 0, 0], [1, 0, 1, 0], [1, 0, 1, 1]]

The extend is a method that takes as argument an iterable and adds its elements to the list. This means that we can use the method by passing lists, tuples, dictionaries and other objects that are eternal as arguments.

lista_principal = [1, 2, 3]
dicionario = {"comida": "pizza", "altura": 1.76}
tupla = ("Cachorro", "Bola")

lista_principal.extend(dicionario)
lista_principal.extend(tupla)

Note that the method extend does not return a new list, it adds the elements by directly modifying the object. So if you want to merge to get a different list, you have to copy the object using the method copy.

4

Use the method extend of the list:

a = [[1, 0, 0, 0], [1, 1, 1, 0], [1, 0, 0, 0]]
b = [[1, 0, 1, 0], [1, 0, 1, 1]]
a.extend(b)
print(a)

That returns the desired value:

[[1, 0, 0, 0], [1, 1, 1, 0], [1, 0, 0, 0], [1, 0, 1, 0], [1, 0, 1, 1]]

Explanation:

The extend method adds all items of the iterable you pass as parameter (in this case the second list) to the original list. The append method, in turn, simply adds the entire object passed by you to the end of the list.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.