Reputation: 2216
While I was going through Google Python Class Day 1 Part 2 at 14:20 - 14:30 Guy says "do not use list.sort
". Also he mentioned that "Dinosaurs use that!" (i.e. it's an old way of doing sorting). But he did not mention the reason.
Can anyone tell me why we should not use list.sort
?
Upvotes: 8
Views: 3170
Reputation: 8813
From https://wiki.python.org/moin/HowTo/Sorting:
You can also use the
list.sort()
method of a list. It modifies the list in-place (and returnsNone
to avoid confusion). Usually it's less convenient thansorted()
- but if you don't need the original list, it's slightly more efficient.
Many people prefer not changing the state of variables (look up the advantages of immutable values/data structures), and so would prefer not to modify the original list like list.sort
does.
Upvotes: 6
Reputation: 3363
I think it is very opinion based, sometimes you need to change an original list and you use .sort(), sometimes you don't need to change it, and you use sorted()
In general, it isn't bad to use .sort()
Upvotes: 7
Reputation: 174696
Because list.sort()
will do an in-place sorting. So this changes the original list. But sorted(list)
would create a new list instead of modifying the original.
Example:
>>> s = [1,2,37,4]
>>> s.sort()
>>> s
[1, 2, 4, 37]
>>> s = [1,2,37,4,45]
>>> sorted(s)
[1, 2, 4, 37, 45]
>>> s
[1, 2, 37, 4, 45]
Upvotes: 14