Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should not use list.sort in python

Tags:

python

sorting

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?

like image 852
Laxmikant Avatar asked Aug 20 '15 07:08

Laxmikant


2 Answers

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]
like image 134
Avinash Raj Avatar answered Oct 21 '22 05:10

Avinash Raj


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

like image 40
svfat Avatar answered Oct 21 '22 04:10

svfat