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))
有帮助吗?

解决方案

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]

其他提示

>>> [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))
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top