2

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?

Coderaemon
  • 3,619
  • 6
  • 27
  • 50

2 Answers2

4

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

If I correctly understand your question, you should be able to use .count() as it does in this earlier question. How can I count the occurrences of a list item in Python?

Community
  • 1
  • 1
  • I don't know what are the items in my list are. I will have to find unique items and then do count for each to find its distribution. I think collections approach is shorter and neater. – Coderaemon Apr 03 '14 at 08:09