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
?
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]
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()
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