Question

I wanted to know if there is an easy way to find all indexes of a list that are empty.

mylist  = [ [1,2,3,4], [] , [1,2,3,4] , [] ]

next((i for i, j in enumerate(mylist) if not j),"no empty indexes found") will return the first empty index of the list, but can I return all of them? It will default to the string "no empty indexes found" if there is no empty indexes.

I want to append all the empty indexes to another list to use.

my_indexes_list.append(next((i for i, j in enumerate(self.list_of_colors) if not j),5))
Was it helpful?

Solution

Use the fact that empty sequences are false in a boolean context, together with a list comprehension:

>>> mylist  = [[1,2,3,4], [] , [1,2,3,4] , []]
>>> [i for i,x in enumerate(mylist) if not x]
[1, 3]

OTHER TIPS

>>> [i for i,x in enumerate(mylist) if x ==[] ]
[1, 3]
empties[]
for s in mylist:
    is len(s) == 0
        empties.append(mylist.index(s))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top