Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why does the sort(with key) function not work as intended?

# A function that returns the frequency of each value:
def myFunc(e):
     return cars.count(e)

cars = ['Ford', 'Ford', 'Ford', 'Mitsubishi','Mitsubishi', 'BMW', 'VW']

cars.sort(key=myFunc) 

print(cars)

Output:

['Ford', 'Ford', 'Ford', 'Mitsubishi', 'Mitsubishi', 'BMW', 'VW']

What I expect:

['BMW', 'VM', 'Mitsubishi', 'Mitsubishi', 'Ford', 'Ford', 'Ford']

Counts:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Ford - 3
Mitsubishi - 2
BMW - 1
VM - 1

It should sort in ascending order of count in the list.

>Solution :

The problem is that you are using cars inside the key function, but .sort is in-place. This causes cars to be unreliable in intermediate calls to the key function.

We can see the problem if we print cars inside the key function:

def myFunc(e):
    print(cars)
    return cars.count(e)


cars = ['Ford', 'Ford', 'Ford', 'Mitsubishi', 'Mitsubishi', 'BMW', 'VW']

cars.sort(key=myFunc)

This outputs

[]
[]
[]
[]
[]
[]
[]

so cars.count will return 0 regardless what element is passed and the list will retain its original order.

Use sorted(...) which is not in-place:

def myFunc(e):
    return cars.count(e)


cars = ['Ford', 'Ford', 'Ford', 'Mitsubishi', 'Mitsubishi', 'BMW', 'VW']

cars = sorted(cars, key=myFunc)

print(cars)

This outputs

['BMW', 'VW', 'Mitsubishi', 'Mitsubishi', 'Ford', 'Ford', 'Ford']

As a side-note, in this case you can use cars.count directly, without defining the wrapper function:

cars = sorted(cars, key=cars.count)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading