how to count multiple items in a list

  • Last Update :
  • Techknowledgy :

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.,If you want to count multiple items in a list, you can call count() in a loop.,Use count() method to find the number of times the specified item appears in the list.

# Count number of occurrences of 'red'
L = ['red', 'green', 'blue']
print(L.count('red'))
# Prints 1
# Count number of occurrences of number '9'
L = [1, 9, 7, 3, 9, 1, 9, 2]
print(L.count(9))
# Prints 3
# Count occurrences of all the unique items
L = ['a', 'b', 'c', 'b', 'a', 'a', 'a']
from collections
import Counter
print(Counter(L))
# Prints Counter({
   'a': 4,
   'b': 2,
   'c': 1
})

Suggestion : 2

If you only want a single item's count, use the count method:

>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3

Use Counter if you are using Python 2.7 or 3.x and you want the number of occurrences for each element:

>>> from collections
import Counter
   >>>
   z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red'] >>>
   Counter(z)
Counter({
   'blue': 3,
   'red': 2,
   'yellow': 1
})

For counting the occurrences of just one list item you can use count()

>>> l = ["a", "b", "b"] >>>
   l.count("a")
1
   >>>
   l.count("b")
2

To count the occurrences of items in l one can simply use a list comprehension and the count() method

[
   [x, l.count(x)]
   for x in set(l)
]

Example:

>>> l = ["a", "b", "b"] >>>
   [
      [x, l.count(x)]
      for x in set(l)
   ]
   [
      ['a', 1],
      ['b', 2]
   ] >>>
   dict((x, l.count(x)) for x in set(l)) {
      'a': 1,
      'b': 2
   }

Example:

>>> l = ["a", "b", "b"] >>>
   from collections
import Counter
   >>>
   Counter(l)
Counter({
   'b': 2,
   'a': 1
})

Here is the script I used:

from __future__
import print_function
import timeit

t1 = timeit.Timer('Counter(l)', \
   'import random;import string;from collections import Counter;n=1000;l=[random.choice(string.ascii_letters) for x in range(n)]'
)

t2 = timeit.Timer('[[x,l.count(x)] for x in set(l)]',
   'import random;import string;n=1000;l=[random.choice(string.ascii_letters) for x in range(n)]'
)

print("Counter(): ", t1.repeat(repeat = 3, number = 10000))
print("count():   ", t2.repeat(repeat = 3, number = 10000)

Another way to get the number of occurrences of each item, in a dictionary:

dict((i, a.count(i)) for i in a)

Here's an example list:

>>> l = list('aaaaabbbbcccdde') >>>
   l['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'e']

There's the list.count method

>>> l.count('b')
4

This works fine for any list. Tuples have this method as well:

>>> t = tuple('aabbbffffff') >>>
   t('a', 'a', 'b', 'b', 'b', 'f', 'f', 'f', 'f', 'f', 'f') >>>
   t.count('f')
6

You can add or subtract with iterables from your counter:

>>> c.update(list('bbb')) >>>
   c['b']
7
   >>>
   c.subtract(list('bbb')) >>>
   c['b']
4

And you can do multi-set operations with the counter as well:

>>> c2 = Counter(list('aabbxyz')) >>>
   c - c2 # set difference
Counter({
      'a': 3,
      'c': 3,
      'b': 2,
      'd': 2,
      'e': 1
   }) >>>
   c + c2 # addition of all elements
Counter({
      'a': 7,
      'b': 6,
      'c': 3,
      'd': 2,
      'e': 1,
      'y': 1,
      'x': 1,
      'z': 1
   }) >>>
   c | c2 # set union
Counter({
      'a': 5,
      'b': 4,
      'c': 3,
      'd': 2,
      'e': 1,
      'y': 1,
      'x': 1,
      'z': 1
   }) >>>
   c & c2 # set intersection
Counter({
   'a': 2,
   'b': 2
})

For large enough arrays, it turns out that

numpy.sum(numpy.array(a) == 1)
numpy.bincount(a)

Code to reproduce the plots:

from collections
import Counter
from collections
import defaultdict
import numpy
import operator
import pandas
import perfplot

def counter(a):
   return Counter(a)

def count(a):
   return dict((i, a.count(i)) for i in set(a))

def bincount(a):
   return numpy.bincount(a)

def pandas_value_counts(a):
   return pandas.Series(a).value_counts()

def occur_dict(a):
   d = {}
for i in a:
   if i in d:
   d[i] = d[i] + 1
else:
   d[i] = 1
return d

def count_unsorted_list_items(items):
   counts = defaultdict(int)
for item in items:
   counts[item] += 1
return dict(counts)

def operator_countof(a):
   return dict((i, operator.countOf(a, i)) for i in set(a))

perfplot.show(
   setup = lambda n: list(numpy.random.randint(0, 100, n)),
   n_range = [2 ** k
      for k in range(20)
   ],
   kernels = [
      counter, count, bincount, pandas_value_counts, occur_dict,
      count_unsorted_list_items, operator_countof
   ],
   equality_check = None,
   logx = True,
   logy = True,
)

Suggestion : 3

November 12, 2021February 22, 2022

Let’s see how we can use the .count() method to count the number of occurrences in a Python list:

# Count the Number of Occurrences in a Python list using.count()
items = ['a', 'b', 'a', 'c', 'd', 'd', 'd', 'c', 'a', 'b']

count_a = items.count('a')
print(f '{count_a=}')

# Returns: count_a = 3

Let’s see what would happen if we pass in an item that does not exist in the list:

# Count the Number of Occurrences in a Python list using.count()
items = ['a', 'b', 'a', 'c', 'd', 'd', 'd', 'c', 'a', 'b']

count_f = items.count('f')
print(f '{count_f=}')

# Returns: count_f = 0

Let’s see how we can use the Counter class to count the number of occurrences of items in a Python list:

# Count the Number of Occurrences in a Python list using Counter
from collections
import Counter
items = ['a', 'b', 'a', 'c', 'd', 'd', 'd', 'c', 'a', 'b']

counts = Counter(items)
print(counts['a'])

# Returns: 3

Let’s see how we can do this using Pandas:

# Count the Number of Occurrences in a Python list using Pandas
import pandas as pd
items = ['a', 'b', 'a', 'c', 'd', 'd', 'd', 'c', 'a', 'b']

counts = pd.Series(items).value_counts()
print(counts.get('a'))

# Returns: 3

Let’s see how we can use the method to count the number of times an item appears in a list:

# Count the Number of Occurrences in a Python list using operator
from operator
import countOf
items = ['a', 'b', 'a', 'c', 'd', 'd', 'd', 'c', 'a', 'b']

count_a = countOf(items, 'a')
print(count_a)

# Returns: 3

Suggestion : 4

The COUNTIFS function takes multiple criteria in range/criteria pairs — each pair contains one range and the associated criteria for that range:,The COUNTIFS function returns the count of cells that meet one or more criteria. COUNTIFS can be used with criteria based on dates, numbers, text, and other conditions. COUNTIFS supports logical operators (>,<,<>,=) and wildcards (*,?) for partial matching.,The Excel COUNTIFS function returns the count of cells that meet one or more criteria. COUNTIFS can be used with criteria based on dates, numbers, text, and other conditions. COUNTIFS supports logical operators (>,...,In the workbook below, we have Color and Price. By adding a second range/criteria pair to COUNTIFS, we can count the combination of Color and Price like this:

= COUNTIFS(A: A, A1)

To create a count of the values that appear in a list or table, you can use the COUNTIFS function. In the example shown, the formula in C5 is:

= COUNTIFS(B: B, B5)
2._
= COUNTIFS(B: B, B5)
= COUNTIFS(B: B, B5)

The COUNTIFS function takes multiple criteria in range/criteria pairs — each pair contains one range and the associated criteria for that range:

= COUNTIFS(range1, criteria1, range2, criteria2, etc.)
2._
= COUNTIFS(range1, criteria1, range2, criteria2, etc.)

In this example, we want to count each value in column B, starting with cell B5. To do this, we can use a formula like this in cell C5:

= COUNTIFS(B: B, B5) // returns 4

The result in cell C5 is 4, since "Red" appears 4 times in column B. As the formula is copied down, it returns a count for each value in B5:B16. Note this formula uses the full column reference B:B for convenience. You can also use an absolute reference like this:

= COUNTIFS($B$5: $B$16, B5)
6._
= COUNTIFS($B$5: $B$16, B5)
= COUNTIFS(range1, criteria1, range2, criteria2, etc.)
= COUNTIFS(B: B, B5) // returns 4

Suggestion : 5

Last Updated : 05 Jul, 2022

Examples: 

Input: lst = [15, 6, 7, 10, 12, 20, 10, 28, 10]
x = 10
Output: 3
10 appears three times in given list.

Input: lst = [8, 6, 8, 10, 8, 20, 10, 8, 8]
x = 16
Output: 0

Output:

8 has occurred 5 times