I put a variable in the list, but the values of the original variable and the variables in the list are not linked

Asked 2 years ago, Updated 2 years ago, 41 views

a = "Ay"
b = "Rain"
c = "C"
d = "D"

abcd = [a, b, c, d]

Even if the value of d is changed, the d value of the abcd variable is not changed. Why is that? I think the opposite is the same

I don't understand why d and abcd[3] play separately. Can the names of the two variables be the same but different? I'd appreciate it if you could tell me why it's not working with each other.

Also, do you have a better site or book to study now? I don't think there's any mention of this in the coding stamp. I don't know if I can't find out.

python list

2022-09-20 20:09

2 Answers

I can't link you for two reasons.

The first is that you assigned the allocation as a literal constant, and the second is that you assigned a different value to the d variable, not to change the d value.

a = "A"
b = "Rain"
c = "C"
d = "D"

#abcd = [a, b, c, d]
abcd = ["A", "B", "C", "D"]

This code you wrote is the same as above. You changed the value of d by assigning a different value to the variable, not changing the value of d itself.

Below is an example for reference.

a = "A"
b = "Rain"
c = "C"
d = ["Dee"]

abcd = [a, b, c, d] #d received the list object.
#abcd = ["A", "B", "C", ["D"] but ["D"] is associated with d.
print(abcd)
c = "CC" 
#In the above case, we assigned "CC" to variable c, not "CC" to "CC".
print(abcd) #There is therefore no change.
d[0] = "Diddy"
#In the above case, we changed the "D" in the 0 position of the ["D"] object to "D" (allocated). Therefore, the other variables (list) that we had in the ["D"] object remain will also be affected.
print(abcd) #The object is reflected and displayed as 'Did' which is the changed value.

[Result]

["A", "B", "C", [D]]
[A, B, C, D]
["A", "B", "Ssi", [D.D]

Think about what the variable is referring to.

Thank you.


2022-09-20 20:09

>>> a='a'
>>> b='b'
>>> c='c'
>>> d='d'
>>> e=[a,b,c,d]
>>> id(a)   #2001198307120
>>> id(b)   #2001198295536
>>> id(c)   #2001197278640
>>> id(d)   #2001197283632
>>> id(e)   #2001199954952
>>> id(e[3]) #2001197283632 (d) other than b,c,d
>>> d=['d']
>>> id(d)   #2001198591240
>>> id(e[3]) #2001197283632 You have d from the previous day. 
>>> e=[a,b,c,d] #redesign
>>> id(a)   #2001198307120
>>> id(b)   #2001198295536
>>> id(c)   #2001197278640
>>> id(d) #2001198591240 (changed)
>>> id(d[0])    #2001197283632
>>> d[0]='b' 
>>> id(d) #2001198591240 (same)
>>> id(d[0]) #2001198295536 (changed)


2022-09-20 20:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.