Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Different methods to initialize 2D arrays gives different outputs [duplicate]

I was solving a few questions involving dynamic programming. I initialized the dp table as -

n = 3
dp = [[False]*n]*n
print(dp)

#Output - [[False, False, False], [False, False, False], [False, False, False]]

Followed by which I set the diagonal elements to True using -

for i in range(n):
    dp[i][i] = True

print(dp)

#Output - [[True, True, True], [True, True, True], [True, True, True]]

However, the above sets every value in dp to True. But when I initialize dp as -

dp = [[False]*n for i in range(n)]

Followed by setting diagonal elements to True, I get the correct output - [[True, False, False], [False, True, False], [False, False, True]]

So how exactly does the star operator generate values of the list?

like image 761
m0bi5 Avatar asked Aug 10 '26 02:08

m0bi5


1 Answers

When you do dp = [[False]*n]*n, you get a list of n of the same lists, as in, when you modify one, all are modified. That's why with that loop of n, you seemingly modify all n^2 elements.

You can check it like this:

[id(x) for x in dp]
> [1566380391432, 1566380391432, 1566380391432, 1566380391432, 1566380391432] # you'll see same values

With dp = [[False]*n for i in range(n)] you are creating different lists n times. Let's try again for this dp:

 [id(x) for x in dp]
 [1566381807176, 1566381801160, 1566381795912, 1566381492552, 1566380166600]

In general, opt to use * to expand immutable data types, and use for ... to expand mutable data types (like lists).

like image 77
chn Avatar answered Aug 12 '26 17:08

chn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!