-2

what I want to manipulate is the first element of v, the second print is supposed to be

[[3], [], [], [], []].

Code:

v = [[]] * 4

print(v)
v[0].append(3);  #what i want to manipulate is the first element of v 
print(v)

output:

[[], [], [], [], []]
[[3], [3], [3], [3], [3]]
depperm
  • 10,606
  • 4
  • 43
  • 67

1 Answers1

0

Python mutable variables (like list) are passed by reference.

v = [[]] * 4

Gives you a list of the same reference, so when you update one element of the list, all other moved with.

v = [[], [], [], []]

Will fix it

Arount
  • 9,853
  • 1
  • 30
  • 43