For example if I have a list like this:
List1 =[7,6,9]
List1 = List1.sort()
The most common reason for data not sorting correctly is due to the leading space ahead of the text. Many people using encounter this problem. The text with leading space is sorted at the top in ascending and at the bottom in descending order sort. Try correcting this, and it will work.
This happens when all the column is not a part of one table, even though it is within one sheet. Make sure that the headings are only present in the first column. Select the complete table region only. Home tab -> Format Table As -> Choose any of the options and check the heading available when prompted.
You cannot sort data by more than one column.
What is sorting? Sorting is the process of arranging data into meaningful order so that you can analyze it more effectively.
list.sort()
sorts the list in-place and returns None
, so you were actually assigning that return value to List1
, i.e None
.
>>> List1 =[7,6,9]
>>> repr(List1.sort())
'None' #return Value of list.sort
>>> List1 #though list is sorted
[6, 7, 9]
On the other hand the built-in function sorted
returns a new sorted list:
>>> List1 =[7,6,9]
>>> sorted(List1)
[6, 7, 9]
>>> List1 #List1 is not affected
[7, 6, 9]
You can assign back the result of sorted
to List1
, but this makes no sense as list.sort
will do the same thing and in lesser time.
>>> List1 = sorted(List1)
>>> List1
[6, 7, 9]
Though the above code was similar to list.sort
, but actually it's a bit different because it returns new list. Example:
>>> List1 =[7,6,9]
>>> List2 = List1 # both List1, List2 point to the same object [7, 6, 9]
>>> List1.sort() # sort List1 in-place, affects the original object
>>> List1, List2
([6, 7, 9], [6, 7, 9]) # both variables still point to the same list
>>> List1 =[7,6,9]
>>> List2 = List1 #same as above
>>> List1 = sorted(List1) #sorted returns a new list, so List1 now points to this new list
>>> List1, List2 #List2 is still unchanged
([6, 7, 9], [7, 6, 9])
Timing comparisons:
>>> from random import shuffle
>>> lis = range(10**5)
>>> shuffle(lis)
>>> %timeit lis.sort()
1 loops, best of 3: 9.9 ms per loop
>>> lis = range(10**5)
>>> shuffle(lis)
>>> %timeit sorted(lis)
1 loops, best of 3: 95.9 ms per loop
So, sorted
should be used only when you don't want to affect the original list and want to assign the sorted version of that list to some other variable.
Apart from lists other data-structures like set, tuples, dicts,etc don't have their own .sort()
method, so sorted
is the only thing you can use there.
>>> s = {1,5,3,6} # set
>>> sorted(s)
[1, 3, 5, 6]
help on sorted
:
>>> print sorted.__doc__
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With