How to find the number of occurrences in a list of tuples in python ?

Published: October 10, 2021

Updated: December 09, 2022

Tags: Python; List; Tuple;

DMCA.com Protection Status

Examples of how to find the number of occurrences in a list of tuples in python :

Create a list of tuples

Let's create a list of tuples:

mylist = [
('a', 'b', 'c',),
('a', 'b', 'c',),
('c', 'b', 'a',),
('a', 'b', ),
('a',)
]

note that

type(mylist) 
type(mylist[0])

gives

<class 'list'>

and

<class 'tuple'>

respectively

Find occurrences of tuples

To find occurrences of tuples in a list, a solution is to use counter from collections

from collections import Counter

counter = Counter(e for e in mylist)

gives

Counter({('a', 'b', 'c'): 2, ('c', 'b', 'a'): 1, ('a', 'b'): 1, ('a',): 1})

Note that here ('a', 'b', 'c') and ('c', 'b', 'a') are considered as different tuples.

Also it is possible to put counter results in a dictionary:

d = dict( counter )

print( d )
print( d.keys() )
print( d[('a', 'b', 'c')] )

gives

{('a', 'b', 'c'): 2, ('c', 'b', 'a'): 1, ('a', 'b'): 1, ('a',): 1}
dict_keys([('a', 'b', 'c'), ('c', 'b', 'a'), ('a', 'b'), ('a',)])
2

Find occurrences of tuples that contains same elements

Another example, find occurrences of tuples that contains same elements. So ('a', 'b', 'c') == ('c', 'b', 'a')

from collections import Counter

counter = Counter(tuple(sorted(t)) for t in mylist)
print(counter)

gives

Counter({('a', 'b', 'c'): 3, ('a', 'b'): 1, ('a',): 1})

Find occurrences of elements in each tuple

To find only occurrences of elements in each tuple, a solution is to do:

import itertools

mylist2 = list(itertools.chain.from_iterable(mylist) )

    print(mylist2)

gives

['a', 'b', 'c', 'a', 'b', 'c', 'c', 'b', 'a', 'a', 'b', 'a']

print( Counter(mylist2) )

gives

Counter({'a': 5, 'b': 4, 'c': 3})

Note: to get only unique elements:

mylist2 = list( set(itertools.chain.from_iterable(mylist)) )
print(mylist2)

gives

['c', 'a', 'b']