When using the . extend() command in Python, how do you store the result in a new object?

Asked

Viewed 30 times

2

Considering the lists:

lista1=["a","b","c","d"] 
lista2=[5,6,7,8]

My goal is to get a new list that has the elements of these two ['a', 'b', 'c', 'd', 5, 6, 7, 8], but preserving them the way they are.

Making lista3=[lista1,lista2], what I got is a list of lists [['a', 'b', 'c', 'd'], [5, 6, 7, 8]], which is of no interest to me.

I tried to do it this way:

lista4=lista1
lista4.extend(lista1)
print(lista4)

Upshot:

['a', 'b', 'c', 'd', 5, 6, 7, 8]

This resulted in what I expected. But by asking lista1 again, it was no longer with the initial configuration, but with the same result above.

print(lista1)
['a', 'b', 'c', 'd', 5, 6, 7, 8]

I thought that using lista4=lista1 and use .extend() in list 4, the lista1 would be as set at the beginning. Could someone explain to me why this occurred and if it has how to get around?

1 answer

3


Just concatenate the lists and assign to a new one:

lista1 = ["a", "b", "c", "d"] 
lista2 = [5, 6, 7, 8]

lista4 = lista1 + lista2

print(lista1) # ['a', 'b', 'c', 'd']
print(lista2) # [5, 6, 7, 8]
print(lista4) # ['a', 'b', 'c', 'd', 5, 6, 7, 8]

In your case it did not work as expected because while doing lista4 = lista1, you made sure lista4 pointed to the same list as lista1 points out (because the variables lista1 and lista4 are actually references to the list - they do not contain the list itself, but a reference to it).

Making an analogy, imagine that lista1 is a sheet of paper with my written address. When making lista4 = lista1, I’m taking another sheet of paper and writing the same address on it.

When doing any operation with these sheets of paper (for example, "deliver this package to the address that is written there"), it makes no difference if it is done at lista1 or lista4. As they both point to the same address, the result will be the package delivered to my house.

Likewise, in doing extend in lista4, this modifies the list for which lista4 is pointing. And how it points to the same list as lista1, this is modified.

Already when concatenating the lists with +, you are creating a new list, keeping the originals intact.

  • 1

    I am used to using R software and it accepts this type of operation, so I got a little lost. Thank you very much for the explanation! It was very educational!

Browser other questions tagged

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