Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index of an inner list in a list of lists

Tags:

python

list

I have a list of lists:

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

I store the address of one of the inner lists in a variable:

>>> c = a[4]

And now I expect to be able to retrieve the index of c (=4) in this way, but it doesn't work:

>>> a.index(c)
0 

The above works when the list contains constants, but it isn't working above. What am I missing?

like image 492
Mayank Avatar asked Sep 26 '22 15:09

Mayank


1 Answers

The issue is that list.index() works also based on equality, not identity, so it returns the index for the first equal element in the list.

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

>>> a = []
>>> b = []
>>> a == b
True
>>> a is b
False
like image 115
Anand S Kumar Avatar answered Sep 30 '22 08:09

Anand S Kumar