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

Active October 10, 2021    /    Viewed 1040    /    Comments 0    /    Edit


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']

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!