Search code examples
pythonlistobject-type

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.


Solution

  • a = [1, 1.23, 'abc', 'ABC', 6.45, 2, 3, 4, 4.98]
    
    sum(isinstance(i, int) for i in a)
    

    which returns

    4