The index of the internal list in the list of lists

I have a list of lists:

>>> a = [list() for i in range(0, 5)] >>> a [[], [], [], [], []] 

I save the address of one of the internal lists in a variable:

 >>> c = a[4] 

And now I expect that I can get the index c (= 4) this way, but it does not work:

 >>> a.index(c) 0 

The above works when the list contains constants, but it does not work above. What am I missing?

+5
source share
1 answer

The problem is that list.index() also works on the basis of equality, not identifier, so it returns the index for the first equal element in the list.

And for lists, equality is checked by first checking that they are both the same list (that is, if both compared lists are the same list object, it immediately returns True), otherwise it is based on the equality of all elements contained in it that is, if two lists have all the elements in the same order, then these lists are equal, therefore empty lists are always equal. Example -

 >>> a = [] >>> b = [] >>> a == b True >>> a is b False 
+4
source

Source: https://habr.com/ru/post/1232422/


All Articles