Skip to content
Advertisement

Python: Counting occurrences of List element within List

I’m trying to count the number of occurrences of elements within a list, if such elements are also lists. The order is also important.

JavaScript

One important factor is that ['a', 'b', 'c'] != ['c', 'b', 'a']

I have tried:

JavaScript

Which both resulted in ['a', 'b', 'c'] = ['c', 'b', 'a'], one thing i didn’t want

I also tried:

JavaScript

Which only resulted in error; since lists can’t be used as keys in dicts.

Is there a way to do this?

Advertisement

Answer

You can’t have list as a key to the dict because dictionaries only allows immutable objects as it’s key. Hence you need to firstly convert your objects to tuple. Then you may use collection.Counter to get the count of each tuple as:

JavaScript
Advertisement