+ 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]?
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 ))
+ 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...
+ 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.
+ 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
+ 1
Doniyorbek thank u. But sorry, I didn't catch. Think your case is little different.
+ 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.
+ 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
0
#Change to
x=[[0]*2 for i in range(2)]
x[0][0]=1
print (x)