1

I'm looking to count the number of occurrences of an empty array within a 2D array in the most efficient manner. For example :

array = [[a,b],[a,b,c],[a],[],[],[],[]]

The answer I would like to get should be 4.

How do we get around doing that without using a lengthy for loop process? It shouldn't also use Numpy, just plain simple Python. I tried .count, but I doesn't quite work with empty arrays.

Lotus
  • 79
  • 1
  • 5

4 Answers4

2

Here is my short solution using the list.count() method:

array = [[a,b],[a,b,c],[a],[],[],[],[]]

print(array.count([])) # 4
Laurent H.
  • 6,316
  • 1
  • 18
  • 40
1
array = [[a,b],[a,b,c],[a],[],[],[],[]]
answer = len([a for a in array if not a])

>>> answer
4
deadvoid
  • 1,270
  • 10
  • 19
0
array = [[1,2],[1,2,3],[1],[],[],[],[]]

print(sum(1 for arr in array if not arr)) # 4
Tanmay jain
  • 814
  • 6
  • 11
0

I would use the array.count([]) method but just introducing an option that has not been displayed

print(len(list(filter(lambda x: x == [], array))))
# 4
vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20