Variable assigned to another parent variable

Asked

Viewed 37 times

0

Hello, I’m having a problem with Python3: When I create a list and assign the value of another variable to that list, when I change the variable the list is changed, code:

lista = ["uau", "nossa"]
lista1 = lista
lista1[0] = "impressionante"
print(lista1, lista)
# retorna ['impressionante', 'nossa'] ['impressionante', 'nossa']

I would like the variable "list" to stop changing and only "list1" to change, I would also like if you could tell me why this happens, thank you.

1 answer

2


Hello,

It turns out that when you do this, you reference one list to another, so in order for you not to create that object reference, you would have to make a copy. Just add the method copy, see:

lista = ["uau", "nossa"]
lista1 = lista.copy()

lista1[0] = "impressionante"

print(lista1, lista) # ['impressionante', 'nossa'] ['uau', 'nossa']

With multidimensional vectors, you can do the following:

from copy import deepcopy

lista = [["uau", "nossa"]]
lista1 = deepcopy(lista)

lista1[0][0] = "impressionante"

print(lista1, lista) # [['impressionante', 'nossa']] [['uau', 'nossa']]
  • 1

    Thank you very much.

  • You are welcome to do so :) If possible mark the answer in ✔

  • You have to wait a while

  • How do I do this with two-dimensional lists? I’m trying and it’s wrong

  • 1

    I edited the answer with an example using multidimensional list :)

Browser other questions tagged

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