+ 3

index()

x=[[0]*2]*2 x[0][0]=1 print (x) why here answer is [1,0][1,0], not [1,0][0,0]?

2nd Aug 2018, 9:12 AM
tardigrade
tardigrade - avatar
9 odpowiedzi
+ 3
HonFu I understand the process, but what is the benefit of this and where it can be useful, why container holds very same list two times. Damn my curious ))
2nd Aug 2018, 11:03 AM
tardigrade
tardigrade - avatar
+ 3
tardigrade, I've also up to now only encountered cases where it was bothersome. A few weeks ago I tried to do a shift schedule script for people on a job. I wanted to model a month, and since we are supposed to write in a DRY fashion, I thought: Hey, let's just model a week and multiply it. But when I started to deal out shifts to people, employee x suddenly got EVERY monday, EVERY tuesday and so on! ^^' I think it was okay if we fully understood, when and how this happens, but that is really all still fuzzy in my head...
2nd Aug 2018, 12:37 PM
HonFu
HonFu - avatar
+ 2
I am also puzzled by that problem. Okay, it is an identity-issue, I see that: the two partial lists are actually the same object, so if we change one, we change 'the other' as well. Alright, but why isn't the result [1,1][1,1] then, since the first index of the partial list gets also multiplied and should have the same identity as the second, no? Also if you just do arr = [0,0]*2, you get one single list with four perfectly distinct elements. With this kind of container operations I always find it hard to anticipate what I will actually get.
2nd Aug 2018, 10:42 AM
HonFu
HonFu - avatar
+ 2
Louis I don't want to get answer what i wrote. I just wondered why the one value (in my case this is 1) can affect to 2 partial list element. That's the matter
2nd Aug 2018, 10:50 AM
tardigrade
tardigrade - avatar
+ 1
Doniyorbek thank u. But sorry, I didn't catch. Think your case is little different.
2nd Aug 2018, 10:29 AM
tardigrade
tardigrade - avatar
+ 1
tardigrade, it is a bit hard to imagine (if you're like me) but the container does not hold two different lists, it holds (a reference to) the very same list two times. a = [1] b = [a, a] a. append(1) ... So if you change a, it changes in both places in b at once.
2nd Aug 2018, 10:57 AM
HonFu
HonFu - avatar
+ 1
you didn't write [0,0]*2 but [[0,0]]*2 since : x=[[0]*2]*2 = [[0,0]]*2 so you had an array which element was an array and the *2 did what it does ... wrote each element of array twice
4th Oct 2018, 4:04 AM
Tomasz Drgas
Tomasz Drgas - avatar
0
#Change to x=[[0]*2 for i in range(2)] x[0][0]=1 print (x)
2nd Aug 2018, 10:44 AM
Louis
Louis - avatar