tic tac toe
tic tac toe

Reputation: 29

Confusion with list.sort() in python

Consider two lists:

list1=[-4,-5,-3]
list2=['-4','-5','-3']

Now if we use

list1.sort()
list2.sort() # in python3 

We get contradictory results:

[-5, -4, -3]
['-3', '-4', '-5']`

Why is it so and how can we do it right!?

Upvotes: 1

Views: 1942

Answers (4)

Tom Dee
Tom Dee

Reputation: 2674

The list1 sort is pretty self explanatory as it is just sorting the numbers numerically.

In list2 the values are stored as strings. So it is comparing and sorting them by the ASCII value. The digit 3 has an ASCII value of 51, 4 has a value of 52 and 5 has a value of 53. So it is working completely correctly, if you want to sort out words this is the way you want to do it.

However if you are just wanting to sort digits in the correct order make sure they are ints like list1. Or you can set the key in the sort method to cast them as ints so it is sorted in the numerical way like this:

list2.sort(key=int)

Upvotes: 8

Hemme02
Hemme02

Reputation: 34

Well this is two arrays with different contents. List1 is an array with numbers, List2 is an array of strings. That's why they don´t sort the same.

Upvotes: 0

Nipun Bhalla
Nipun Bhalla

Reputation: 54

The elements in list [-4,-5,-3] are numbers whereas elements in list ['-4','-5','-3'] are strings(because the numbers in the list are between 'single_qoutes').

So, the reason for getting contradictory results is that when you sort numbers, you get back [-5, -4, -3], which is sorted by there numerical value.

When you sort the other list with strings, it sorts it by alphabetically wherein 3, 4 and 5 would be correct way ('-' is the first character and 3, 4 and 5 are the characters after it.) to sort it based on its ASCII value.

So if you want to sort integers, don't include them between quotes.

Upvotes: 2

sanyassh
sanyassh

Reputation: 8500

  • Why is it so?

You can check that '-3' < '-4'. String compasion checks first symbols '-' == '-', check second symbol '3' < '4', so '-3' < '-4'.

  • How we can do it right?

It depends on what you call right. If you want to sort integers, Python does it right. If you want to sort string, Python does it right too.

Upvotes: 1

Related Questions