unsupported operand type(s) for +: 'int' and 'tuple'

6.8k views Asked by At

I need to complete a task where I am given a list of names and grades for each name and I need to sort these out by highest to lowest grade. However if two names have the same grades then sort those names out in alphabetical order. This is the problem I am presented with. I am required to keep the sort function on one line.

a = [('Tim Jones', 54), ('Anna Smith', 56), ('Barry Thomas', 88)]
sum(sorted(a,key=lambda x: x[1]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'tuple'

Any idea on how this can be resolved? I've tried to work it out for many days now.

UPDATED

Ok thanks for helping me work out that one, however there is another scenario where I need to resolve as well.

a = [('Tim Jones', 'C'), ('Anna Smith', 'B'), ('Barry Thomas', 'A')]
sorted(a,key=lambda x: -x[1])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
TypeError: bad operand type for unary -: 'str'

So this is the current situation basically all I need to do now is organise the list so then it goes from highest grade to lowest grade.

2

There are 2 answers

0
Bill Lynch On BEST ANSWER

Let's note that sorted() will return a copy of your original list, but sorted:

>>> a = [('Tim Jones', 54), ('Anna Smith', 56), ('Barry Thomas', 88)]
>>> sorted(a,key=lambda x: x[1])
[('Tim Jones', 54), ('Anna Smith', 56), ('Barry Thomas', 88)]

Python itself will fail when attempting to sum these three tuples, because it doesn't really have any clear meaning.

('Tim Jones', 54)
('Anna Smith', 56)
('Barry Thomas', 88)
0
Todd Tao On

The sorted() function return a tuple list. So you can't sum them up because sum() suppose to receive a sequence of numerics.

The second one is because you have a minus (-) before the x[1] while x[1] is a string. You can't have a negative string.

>>> a = [('Tim Jones', 'C'), ('Anna Smith', 'B'), ('Barry Thomas', 'A')]
>>> sorted(a,key=lambda x: x[1])

If you wanna sort those names out in alphabetical order when grades are the same, then use tuple (x[1],x[0]) as the sorted key.

>>> a = [('Tim Jones', 54), ('Anna Smith', 56), ('Barry Thomas', 88),('Array Thomas', 88)]
>>> sorted(a,key=lambda x: (x[1],x[0]))
[('Tim Jones', 54), ('Anna Smith', 56), ('Array Thomas', 88), ('Barry Thomas', 88)]