0

I am new to python programming & was trying a hackkerank question based on nested lists to print the name(s) of any student(s) having the second lowest grade. Link for the question: https://www.hackerrank.com/challenges/nested-list/problem?isFullScreen=true Below is my code and I am getting unhashable type:'list' error:

if __name__ == '__main__':
    i = int(input("Enter the length"))
    name=[]
    score=[]
    for _ in range(i):
        name.append(input())
        score.append(float(input()))
my_list=[[name,score] for _ in range(i)]
us=list(set([score for name,score in my_list]))
us.sort()
if len(us)==1:
    sl=us[0]
else:
    sl=us[1]
student=[name for name,score in my_list if score==sl]
student.sort()
print(student)

Please advise what is wrong with this code. I have checked all articles regarding this error but nothing fixed it.

  • 1
    `us=list(set([score for name,score in my_list]))` You're calling `set()` on a list-of-lists, and you can't do that. – John Gordon Aug 10 '20 at 01:07

2 Answers2

0

The error is caused by this line:

us=list(set([score for name,score in my_list]))

You cannot create a set on a list containing nested lists.

Gavin Wong
  • 1,254
  • 1
  • 6
  • 15
0

The issue comes from the line

us=list(set([score for name,score in my_list]))

and I believe the same issue would arise from the line

student=[name for name,score in my_list if score==sl]

The output of the score list looks like a list of lists which sets cannot operate on

[[37.21, 37.21, 37.2, 41.0, 39.0], [37.21, 37.21, 37.2, 41.0, 39.0], [37.21, 37.21, 37.2, 41.0, 39.0], [37.21, 37.21, 37.2, 41.0, 39.0], [37.21, 37.21, 37.2, 41.0, 39.0]]

If you check your my_list it looks like this

[[['Harry', 'Berry', 'Tina', 'Akriti', 'Harsh'], [37.21, 37.21, 37.2, 41.0, 39.0]], [['Harry', 'Berry', 'Tina', 'Akriti', 'Harsh'], [37.21, 37.21, 37.2, 41.0, 39.0]], [['Harry', 'Berry', 'Tina', 'Akriti', 'Harsh'], [37.21, 37.21, 37.2, 41.0, 39.0]], [['Harry', 'Berry', 'Tina', 'Akriti', 'Harsh'], [37.21, 37.21, 37.2, 41.0, 39.0]], [['Harry', 'Berry', 'Tina', 'Akriti', 'Harsh'], [37.21, 37.21, 37.2, 41.0, 39.0]]]

You need to try and build your list to look like this

students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]]

Not going to post the actual answer but hope this helps you understand your error

Resources: How is set() implemented? , http://net-informations.com/python/iq/unhashable.htm#:~:text=TypeError%3A%20unhashable%20type%3A%20'list'%20usually%20means%20that%20you,it%20will%20result%20an%20error.&text=when%20you%20use%20a%20list,lists%20can't%20be%20hashed.

Smurphy0000
  • 76
  • 1
  • 7