Skip to content

Python count occurrences in list of lists

  • by

Just use Counter from collections to count occurrences in the list of lists in Python. You have to convert to tuple because list is an unhashable type.

Python count occurrences in the list of lists

Simple example code loop through a set of your list and print each item with its count() from the original list:

from collections import Counter

A = [['x', 'y'], ['a', 'b'], ['c', 'f'], ['e', 'f'], ['a', 'b'], ['x', 'y']]

new_A = map(tuple, A)

final_count = Counter(new_A)

# final output:
for i in set(map(tuple, A)):
    print('{} = {}'.format(i, A.count(list(i))))

Output:

Python count occurrences in the list of lists

Using Counter with list of lists

Using generator expression with set:

>>> from collections import Counter
>>> seq = [['a','b','a','c'], ['a','b','c','d']]
>>> Counter(x for xs in seq for x in set(xs))
Counter({'a': 2, 'c': 2, 'b': 2, 'd': 1})

Responding to the comment, Without generator expression:

>>> c = Counter()
>>> for xs in seq:
...     for x in set(xs):
...         c[x] += 1
...
>>> c
Counter({'a': 2, 'c': 2, 'b': 2, 'd': 1})

Do comment if you have any doubts or suggestions on this Python list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading