0

Take a look at this code

a=[[0]*3]*3
a[1][1]=1
for x in a:
    print(*x)

#output
# 0 1 0
# 0 1 0
# 0 1 0

and take a look at this code

a=[
[0,0,0],
[0,0,0],
[0,0,0]
]
a[1][1]=1
for x in a:
    print(*x)

#output
# 0 0 0
# 0 1 0
# 0 0 0

I do believe that in both cases , the array a is same. But why the results are different then.

3
  • 1
    its not the same, the first example you are creating one list and copying it three times. in the second example you create three seperate lists Commented Dec 23, 2019 at 15:09
  • @ChrisDoyle yes but i'am only modifying one element of second list(in first case) and it got applied on all . I'm wondering why ? Commented Dec 23, 2019 at 15:11
  • 1
    yeah but you have only one list in the first case. its like saying a=[1, 2, 3]; b=a; b[0]=9. In this example yo have one list only and a and B both point to the same list, so changing the element in b will change it in a also since they both point to same list. In your first example you do the same thing. you create one list then make 3 copies that point to that 1 list. So if you make a change in either of the copies it will reflect in all of them since there is only one list and they all point to it Commented Dec 23, 2019 at 15:14

1 Answer 1

2

In the first exmaple you are creating one list and then copying it three times. So each copy points to the original list, we can see this by printing the id of the object.

a=[[0]*3]*3
a[1][1]=1
for x in a:
    print(id(x))

#OUTPUT
2330620420744
2330620420744
2330620420744

In the second example you create 3 separate lists

a=[
[0,0,0],
[0,0,0],
[0,0,0]
]
a[1][1]=1
for x in a:
    print(id(x))

#OUTPUT
2330620420680
2330648632008
2330653113224

If you want to create a 2d list like that you can use range function to create x many lists.

a = [[[0] for _ in range(3)] for _ in range(3)]
a[1][1] = 1
for x in a:
    print(id(x))

#OUTPUT
2475065760136
2475067183944
2475067184328
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Man, I got it now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.