Removing Empty Counter () Objects from the List

I have a simple list of counters:

> counter_list
Counter({'Pig': 1}), Counter(), Counter({'Chicken': 3})

I cannot find an easy way to delete an empty counter.

I tried using

counter_list += Counter()

according to the documentation, no luck.

del 

It seems that only deleting the contents of the counter, not the actual counter, and at best just creates a more empty counter.

Any advice is welcome and apologize in advance for the future forehead-slapper.

+4
source share
3 answers

Use list comprehension to create a new one counter_list:

counter_list = [item for item in counter_list if item]

This works because an empty counter Falsish, not an empty counter, is Truish:

In [27]: bool(collections.Counter())
Out[27]: False

In [28]: bool(collections.Counter([1]))
Out[28]: True
+4
source

Try:

counter_list[:] = (c for c in counter_list if c)
+1
source

, item, "Falseish" ( , , len)

counter_list = [item for item in counter_list if len(item) != 0]
+1

All Articles