Reputation: 29
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
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 int
s like list1
. Or you can set the key in the sort method to cast them as int
s so it is sorted in the numerical way like this:
list2.sort(key=int)
Upvotes: 8
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
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
Reputation: 8500
You can check that '-3' < '-4'
. String compasion checks first symbols '-' == '-'
, check second symbol '3' < '4'
, so '-3' < '-4'
.
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