Sha
Sha

Reputation: 1

TypeError:'int' object is not callable

In python I got a "TypeError: 'int' obejct is not callable".I had read other posts but I still can't figure out why it is like this.

def sort_last(tuples):
    sorted_tuples = [sorted(tuples,key=tuple[-1]) for tuple in tuples]
return sorted_tuples

Then I got:"TypeError: 'int' object is not callable."Appreciation for any suggestions and comment

Upvotes: 0

Views: 2153

Answers (1)

PM 2Ring
PM 2Ring

Reputation: 55499

You need to pass a function as the key argument of sorted (and sort, max, and min).

Here's a repaired version of your code, using a lambda function.

def sort_last(tuples):
    sorted_tuples = [sorted(tuples,key=lambda t: t[-1]) for tuple in tuples]
    return sorted_tuples

However, that code is a bit... strange. If your objective is to sort a list of tuples by the last item in each tuple, you can simply do this:

def sort_last(tuples):
    return sorted(tuples, key=lambda t: t[-1])

a = [(1,2,10), (5,6,8), (3,4,9)]
print(sort_last(a))

output

[(5, 6, 8), (3, 4, 9), (1, 2, 10)]

Although that works we can improve the efficiency by using the itemgetter function.

from operator import itemgetter

def sort_last(tuples):
    return sorted(tuples, key=itemgetter(-1))

Upvotes: 3

Related Questions