0

When I do an exercise, I want to generate a m*n list , and all the elements are 0. I find an interesting question:

# first way
a = [[0]*n]*m
a[0][0]=1
# then I find a[1][0]=1,a[2][0]=1....

# second way
b = [[0 for _ in range(n)] for _ in range(m)]
b[0][0]=1
# in this way, I get the normal effect

I am confused about the first way, what is the * means for list?

Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
digger
  • 121
  • 2
  • 4

1 Answers1

0

The * operator essentially takes the old list, and recreates it n times. The new items are the same (the same references) as the old ones, but the list if n times as long.

The original list is not modified, where simply appending new copies to the end would modify it.

Eg:

[1,2,3] * 3 = [1,2,3,1,2,3,1,2,3]

[[1],[2]] * 3 = [[1],[2],[1],[2],[1],[2]]

>>> myfunc = lambda: None
>>> a = [myfunc]
>>> a
[<function <lambda> at 0x03193468>]
>>> b = a * 2
>>> b
[<function <lambda> at 0x03193468>, <function <lambda> at 0x03193468>]
>>> a
[<function <lambda> at 0x03193468>]
>>> b is a
False
>>> a is b
False

Achieving the 'same' thing with append:

>>> X = [1,2]
>>> a = X.copy()
>>> n = 2
>>> b = a
>>> for i in range(n-1):
        for j in X:
            b.append(j)

>>> b
[1,2,1,2]
>>> a
[1,2,1,2]
>>> X
[1,2]
>>> a is b
True
>>> b is a
True
Ed Ward
  • 2,333
  • 2
  • 10
  • 16