Count - my function throws a "unhashable type: 'list'" error


#1



https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/2/1?curriculum_id=4f89dab3d788890003000096#


Your function crashed on ([7.8, [], 7, 'buggy'], 7) as input because your function throws a "unhashable type: 'list'" error.


My solution is to using a dictionary to store the object in list as key and its count as value, but at last it can't handle the object '[]' as the key of the dictionary. Any ideas?


def count(sequence, item):
    t ={}
    for s in sequence:
        if s in t:
            t[s] = t[s]+1
        else:
            t[s] =1
            
    if item in t:
        return t[item]
    else:
        return 0


#4

"unhashable type: 'list'"

You can't use a list as key of a dictionary.
like this..

d ={}
d[[1,2,3,4]] = "Ryan" # will throw an error

when It checks the code at input where a list contains another list,Then it throws that error.


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.