Recessive
Recessive

Reputation: 1939

Python strange behaviour when sorting a list of tuples

I have a function that looks like the following:

def f(lst, c):

    scored_vals = []
    for i in lst:
        scored_vals += [(i.value/i.weight, i)]
    scored_vals.sort()

    return scored_vals

This function crashes every time it reaches scored_vals.sort(). The argument lst is a list comprised of Items, where the Item class looks like the following:

class Item():

    def __init__(self, weight=0, value=0):
        self.weight = weight
        self.value = value

And the argument c is just an integer.

The error thrown is below:

    scored_vals.sort()
TypeError: '<' not supported between instances of 'Item' and 'Item'

I find this very strange, because normally when you call python sort, it only compare the first item of each tuple in order to sort the list, so if you create the list yourself like below:

lst = [(201.0, Item()), (350.0, Item()), (202.0, Item()), (100.0, Item()), (500.0, Item()), (203.0, Item())]

Then do:

lst.sort()

It throws no error.

Upvotes: 1

Views: 185

Answers (1)

Recessive
Recessive

Reputation: 1939

It is because of the method python uses in sorting tuples/lists. If it finds a value that is equivalent, it will go to the second value in the tuple/list. This means that the error will only occur if the tuples have equivalent values as their first index. For example, the following will throw an error:

lst = [(200.0, Item()), (350.0, Item()), (200.0, Item()), (100.0, Item()), (500.0, Item()), (200.0, Item())]
lst.sort()

But this will not:

lst = [(201.0, Item()), (350.0, Item()), (202.0, Item()), (100.0, Item()), (500.0, Item()), (203.0, Item())]
lst.sort()

Upvotes: 1

Related Questions