0

I wanted to efficiently set a bunch of variables to an empty list. However, using this method, operations on one variable seem to apply to all:

>>> r1,r2,r3,r4,r5,r6,r7,r8=[[]]*8
>>> r1
[]
>>> r1+=[2]
>>> r1,r2
([2], [2])

Why is this? Also, what is the most efficient method that leaves each variable independent?

doublefelix
  • 952
  • 1
  • 9
  • 22
  • Why not just have a list of lists? As opposed to 8 variables? Or even a dictionary? – Ffisegydd Jan 01 '15 at 23:44
  • @Ffisegydd interesting. Question about what you linked: If the syntax [x]*4 creates a 4 item list whose contents all reference the same object, why doesn't [[x]*4]*2 do the same, but with 8 objects total? Why was only the first element of each inner list changed? – doublefelix Jan 01 '15 at 23:55

1 Answers1

1

Doing [[]]*8 creates a list of eight references to the same list object. That is why they all get affected when you update one. To make eight unique lists, use a generator expression:

r1,r2,r3,r4,r5,r6,r7,r8 = ([] for _ in range(8))

You might also use a list comprehension:

r1,r2,r3,r4,r5,r6,r7,r8 = [[] for _ in range(8)]