1

Here is the example:

>>> x = ["a","b","c"]
>>> yy = [x] * 3
>>> yy
[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
>>> yy[0][0] = 'A'
>>> yy
[['A', 'b', 'c'], ['A', 'b', 'c'], ['A', 'b', 'c']]
>>>

When I do yy[0][0] = 'A', it replaced to all the first element of the sub-list. What I got from here is when I do [x] * 3, it creates some reference to list x but not sure how really it works. Could some one please explain?

vvvvv
  • 25,404
  • 19
  • 49
  • 81
James Sapam
  • 16,036
  • 12
  • 50
  • 73

1 Answers1

3

[x]*3 creates 3 references to the same list. You have to create three different lists:

>>> yy = [list('abc') for _ in range(3)]
>>> yy[0][0]='A'
>>> yy
[['A', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]

The first line creates a new list using a list comprehension that loops 3 times.

Using id(), you can visualize that the same list reference is duplicated:

>>> x=list('abc')
>>> id(x)
67297928                                  # list object id
>>> yy=[x]*3                              # create a list with x, duplicated...
>>> [id(i) for i in yy]
[67297928, 67297928, 67297928]            # same id multipled
>>> yy = [list('abc') for _ in range(3)]  
>>> [id(i) for i in yy]
[67298248, 67298312, 67297864]            # three different ids
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251