8

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?

3 Answers 3

14

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]
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for reply. Is there any other disadvantage of using that?
@Laxmikant I don' t think doing a in-place sorting is a disadvantage, it is more efficient (according to python doc), and probably the only way to do it if you have a very big list. One "real" disadvantage is that it is only defined for list, while sorted works on any iterable, so if one day you decide that you need to use something else than list, you'll be stuck :)
@Holt - Thanks for the reply
7

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

Comments

6

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 returns None to avoid confusion). Usually it's less convenient than sorted() - 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.

2 Comments

Surely people who preferred immutable data structures would be using a tuple, not a list?
Agreed, but you're using someone else's code and want to have minimal impact, it still holds true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.