Counting similar list element in a list
Question: I have a list of lists

    
    
    list = [[1,0],[1,2],[1,1],[1,0]]
    

Now I want to count the number of occurrences similar list elements in the
above list. e;g; `[1,0]:2, [1,2]:1, [1,1]:1`

I did

    
    
    import collections
    print Counter(list)
    

It throws error:

    
    
     Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/local/lib/python2.7/collections.py", line 352, in __init__
        self.update(iterable, **kwds)
      File "/usr/local/lib/python2.7/collections.py", line 434, in update
        self[elem] = self_get(elem, 0) + 1
    TypeError: unhashable type: 'list'
    

What am i doing wrong?


Answer: `Counter` is internally a dictionary. The keys of the dictionaries should be
hashble. But lists are mutable and they are not hashable. That is you are not
able to use `Counter` as it is.

One option is to convert the nested list elements to tuples

    
    
    my_list = [[1,0],[1,2],[1,1],[1,0]]
    from collections import Counter
    print Counter(map(tuple, my_list))
    # Counter({(1, 0): 2, (1, 2): 1, (1, 1): 1})
    

If the list is too big, then you can use a generator expression like this

    
    
    print Counter(tuple(item) for item in my_list)
    

this will avoid creating a new list in memory, unlike `map`. And using tuples
work because tuples are immutable and are hashable.

