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.

3
  • check stackoverflow.com/questions/53513/… Commented Oct 5, 2018 at 15:18
  • @cryptonome Doesn't exactly quite address my problem being it a 2D array and counting each empty array in a easy manner. Commented Oct 5, 2018 at 15:20
  • This is a list not an array Commented Oct 5, 2018 at 15:25

4 Answers 4

2

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

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

print(array.count([])) # 4
Sign up to request clarification or add additional context in comments.

1 Comment

damn, this is better
1
array = [[a,b],[a,b,c],[a],[],[],[],[]]
answer = len([a for a in array if not a])

>>> answer
4

Comments

0
array = [[1,2],[1,2,3],[1],[],[],[],[]]

print(sum(1 for arr in array if not arr)) # 4

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.