+ 2

List operators

a = [1, 2, 3] b = a b[0] = 3 print(a) output is 3, 2, 3 why is a here behaving like b? with integers it works fine: a = 1 b = a b = 2 print(a) output is 1

1st Jun 2017, 7:51 PM
Cilveeks
2 Respostas
+ 9
This is how lists work in Python. Instead of being just a collection of values, they should be regarded as pointers to memory addresses where those values are stored. So assigning a variable to a list like you did makes both point to the same addresses. If a value is changed there, both pointers get changed. In order to make a "copy" of a list, you should use the following syntax: b = a[::] That shall produce a slice of a and attribute it to b. Since the slice will be equal to the whole length of a list, you will effectively get a copy of a at b.
1st Jun 2017, 8:02 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
0
output should be 3,2,3
1st Jun 2017, 8:00 PM
Amarie