index()-like behavior that returns all occurences...

Martin von Loewis loewis at informatik.hu-berlin.de
Fri Dec 21 11:44:10 EST 2001


Lorin Hochstein <hawkestein at my-deja.com> writes:

> I've got a list of lists, something like this:
> 
> x = [ [1], [1,2], [], [1,2,3], [], [2], [12] ]
> 
> I want to find the index of all of the empty lists.
[...]
> I know there's an index method of list, such that x.index([]) would 
> return "2". But I want all of the indexes, not just the first one. Is 
> there a simple way to do this (besides the obvious for-loop approach)?

List comprehension may be not that obvious

>>> [i for i in range(len(x)) if x[i] == []]
[2, 4]

HTH,
Martin



More information about the Python-list mailing list