Copy the value of a list variable to a python variable

Asked

Viewed 993 times

2

I’m declaring a variable X with the value of another Y using =, but when having do a append in the variable X, to Y also changes.

Code:

'''
Resultado obtido:
['casaRJ', 'casaSP', 'casaDF', 'apRJ', 'apSP']                                                                                
['casaRJ', 'casaSP', 'casaDF', 'apRJ', 'apSP']

Resultado esperado:
['casaRJ', 'casaSP', 'casaDF']                                                                                
['casaRJ', 'casaSP', 'casaDF', 'apRJ', 'apSP']

'''

variavel_casas = ['casaRJ', 'casaSP', 'casaDF']
variavel_outros = ['apRJ', 'apSP', 'apDF']

principal = variavel_casas
suporte = variavel_casas

if 'casaRJ' in str(variavel_casas): suporte.append('apRJ')
if 'casaSP' in str(variavel_casas): suporte.append('apSP')

print(principal)
print(suporte)

How could I solve this? And why is this happening? Where is the problem in the code, and in what ways could I do it properly?

  • 1

    Why are you converting the list to string, if the test with in also works with lists?

  • I didn’t know, I’m still learning these details. Thanks for the tip @Gustavosampaio

1 answer

3


In python when it comes to container variables (lists, dictionaries, etc) the idea is slightly different from other languages, when vc does var1 = [value1, value2..], var1 works as a kind of "incidental" to the address (in memory) of the list, so if you do: var2 = var1, vc is just creating a new "label" for the list address, see this example:

casas1 = ['casa1', 'casa2', 'casa3']
casas2 = casas1
casas2[0] = 'casa99'

print(casas1)
['casa99', 'casa2', 'casa3']

See the ids of variable:

id(casas1)
140096910106120

id(casas2)
140096910106120

To solve the problem you need to use the method copy(), see the same example, now with copy():

casas1 = ['casa1', 'casa2', 'casa3']
casas2 = casas1.copy()
casas2[0] = 'casa99'

print(casas1)
['casa1', 'casa2', 'casa3']

See that now the ids are different:

id(casas1)
140096885079112

id(casas2)
140097875390664

If Voce wants to copy the variables, in the lines where you do:

principal = variavel_casas
suporte = variavel_casas

Should do:

principal = variavel_casas.copy()
suporte = variavel_casas.copy()
  • It is only possible to copy the value of the variable of type list ? I can do with primitive types with string and int ?

  • @Robsonsilva, Inside the space here I will try to explain (test in a python shell): if you do a="a" and then b=a vc creates the object str a and then make a copy of that object to b, would have how True if it did a==b or id(a)==id(b). If I did b="b" would be creating a new object to b and the two previous expressions would return False.

Browser other questions tagged

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