user3896917
user3896917

Reputation:

count how many of an object type there are in a list Python

If I have a list in python:

a = [1, 1.23, 'abc', 'ABC', 6.45, 2, 3, 4, 4.98]

Is there a very easy way to count the amount of an object type there are in a? Something simpler than the following but produces the same result:

l = [i for i in a if type(a[i]) == int]
print(len(l))

Hopefully I made myself clear.

Upvotes: 8

Views: 13168

Answers (5)

dtheodor
dtheodor

Reputation: 5060

Use the Counter !

from collections import Counter

type_counts = Counter(type(x) for x in a)

assert type_counts[int] == 4
assert type_counts[float] == 3
assert type_counts[str] == 2

This won't help you if you want to count all types and subtypes of a particular type though. For instance, the basestring type does not appear in the results and I can't use the above code to count it.

Upvotes: 6

dawg
dawg

Reputation: 104102

Another way:

>>> a = [1, 1.23, 'abc', 'ABC', 6.45, 2, 3, 4, 4.98]
>>> len(filter(lambda e: isinstance(e, int), a))
4

You should know that any approach that uses isinstance will count True or False as an int since bool is a subclass of int:

>>> isinstance(False, int)
True
>>> type(False)==int
False

So if the distinction between int and bool matters, use type(whatever)==int instead.

Upvotes: 0

Raymond Hettinger
Raymond Hettinger

Reputation: 226754

There are many ways to do it.

Here's one that takes advantage of the list fast map() function and the C-speed list.count() method using them both as they were intended:

>>> a = [1, 1.23, 'abc', 'ABC', 6.45, 2, 3, 4, 4.98]
>>> map(type, a).count(int)
4

In Python 3, map() returns an iterator so you need a small modification, list(map(type, a)).count(int).

The other approaches using sum() and Counter() as also reasonable (readable and used as intended) but are a bit slower.

Upvotes: 10

Aaron Hall
Aaron Hall

Reputation: 395913

a = [1, 1.23, 'abc', 'ABC', 6.45, 2, 3, 4, 4.98]

sum(isinstance(i, int) for i in a)

which returns

4

Upvotes: 5

Blckknght
Blckknght

Reputation: 104852

Use isinstance to do your type checks, and then sum the Boolean values to get the count (True is 1, False is 0):

sum(isinstance(x, int) for x in a)

Upvotes: 14

Related Questions