0

I got confused by the two similar expressions but with different results:

1)
b=[[1,2],[3,4]]
for a in b:
    c=a+[5]
    a=c
print(b)

2)
b=[[1,2],[3,4]]
for a in b:
    c=a+[5]
    a[:]=c
print(b)

and the results:

1) [[1, 2], [3, 4]]
2) [[1, 2, 5], [3, 4, 5]]

why using a[:] in for loop would alter the original b list?

thanks in advance :) .. I am very new to Python

1 Answers1

0

In example (1) 'a' references the sub-list only at first. When you re-assign that, the reference just changes, and therefore there is no effect on the original 'a' in 'b'.

In example (2), 'a's reference is kept since you don't reassign it, rather you're saying 'c' should be copied to the contents of 'a' because of the [:] operator on the LHS. So the reference doesn't change and the changes naturally are a part of 'b' already

user37309
  • 597
  • 5
  • 14