Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Count Elements in a List of Objects with Matching Attributes

People also ask

How do you count elements in a list in Python?

The most straightforward way to get the number of elements in a list is to use the Python built-in function len() . As the name function suggests, len() returns the length of the list, regardless of the types of elements in it.

How do I count multiple elements in a list Python?

If you want to count multiple items in a list, you can call count() in a loop. This approach, however, requires a separate pass over the list for every count() call; which can be catastrophic for performance. Use couter() method from class collections , instead.

How do you count similar items in a list?

If you want to count duplicates for a given element then use the count() function. Use a counter() function or basics logic combination to find all duplicated elements in a list and count them in Python.

Can you use count on a list in Python?

Python count The count() is a built-in function in Python. It will return the total count of a given element in a list. The count() function is used to count elements on a list as well as a string.


class Person:
    def __init__(self, Name, Age, Gender):
        self.Name = Name
        self.Age = Age
        self.Gender = Gender


>>> PeopleList = [Person("Joan", 15, "F"), 
              Person("Henry", 18, "M"), 
              Person("Marg", 21, "F")]
>>> sum(p.Gender == "F" for p in PeopleList)
2
>>> sum(p.Age < 20 for p in PeopleList)
2

I know this is an old question but these days one stdlib way to do this would be

from collections import Counter

c = Counter(getattr(person, 'gender') for person in PeopleList)
# c now is a map of attribute values to counts -- eg: c['F']

I found that using a list comprehension and getting its length was faster than using sum().

According to my tests...

len([p for p in PeopleList if p.Gender == 'F'])

...runs 1.59 times as fast as...

sum(p.Gender == "F" for p in PeopleList)

I prefer this:

def count(iterable):
    return sum(1 for _ in iterable)

Then you can use it like this:

femaleCount = count(p for p in PeopleList if p.Gender == "F")

which is cheap (doesn't create useless lists etc) and perfectly readable (I'd say better than both sum(1 for … if …) and sum(p.Gender == "F" for …)).


Personally I think that defining a function is more simple over multiple uses:

def count(seq, pred):
    return sum(1 for v in seq if pred(v))

print(count(PeopleList, lambda p: p.Gender == "F"))
print(count(PeopleList, lambda p: p.Age < 20))

Particularly if you want to reuse a query.