-1

I have a list of lists in python.

z=[[0]*6]*7

Since all elements are 0. But now if i want to change an individual element within a list e.g

z[0][0]=2

This should change the first element of the first list. But it actually changes the first element of all elements. This is so illogical to me. Can some one help.

 [2, 0, 0, 0, 0, 0],
 [2, 0, 0, 0, 0, 0],
 [2, 0, 0, 0, 0, 0],
 [2, 0, 0, 0, 0, 0],
 [2, 0, 0, 0, 0, 0],
 [2, 0, 0, 0, 0, 0]]
tschale
  • 975
  • 1
  • 18
  • 34
irfan aziz
  • 11
  • 4

1 Answers1

1

That's a classical "programmer's trap" in python.

l = [ 0 ] * 6

creates a list containing six times a reference to the same python object, here, the numerical constant 0.

Now, setting

l[0] = 1 

will replace the first reference to the const 0 object by a reference to another object, the const 1 object.

Now, let's look at

z=[[0]*6]*7

This first creates a list containing six references to the const 0 object, and then it creates a list containing seven references to that single six-element list.

Now,

z[0]

will give you the first element from z, which is simply the same as all the six other elements.

Proof:

print id(z[0]) == id(z[1])

different objects have different IDs.

So you never actually made a list of different lists, but just the same list all over.

You can actually create different sublists and put them into one by doing something like

z = [ [0]*6 for _ in range(7) ]

However, I get the feeling you actually might want to use matrices – if that's really the case, numpy's ndarray is what you're after, because:

import numpy
z = numpy.ndarray((7,6))

actually gives you a matrix with 42 numeric elements.

Marcus Müller
  • 34,677
  • 4
  • 53
  • 94