简体   繁体   中英

How to find all indexes of a list that are empty in Python

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM