0

This is my code:

n = 5
r = 6
C1 = [[0 for x in range(r+1)] for x in range(n+1)]
print(C1)
print()
C1[4][3] = 4
print(C1)

print()
print()

C2 = [[0] * (r+1)] * (n+1)
print(C2)
print()
C2[4][3] = 4
print(C2)

This is the output:

[[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]

[[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 4, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]


[[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]

[[0, 0, 0, 4, 0, 0, 0], [0, 0, 0, 4, 0, 0, 0], [0, 0, 0, 4, 0, 0, 0], [0, 0, 0, 4, 0, 0, 0], [0, 0, 0, 4, 0, 0, 0], [0, 0, 0, 4, 0, 0, 0]]

Why is it that when I use the 'for-range' way, I'm getting the right answer, but the []*n method is giving me the wrong answer? Both produce the same 2D array but when I try to modify it, I'm getting 2 different results!

1 Answers1

1

The difference is that:

y2 = [foo() for _ in range(3)]

is equivalent to:

y2 = [foo(), foo(), foo()]

i.e. the expression is re-evaluated each time. Whereas:

y1 = [foo()] * 3

is equivalent to:

x = foo()
y1 = [x, x, x]

In your case, rather than foo() you're making a new list. So in the first case you get separate inner lists, whereas in the second case you get the same inner list referred to multiple times in the outer list.

Jim Oldfield
  • 674
  • 3
  • 8