Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in python I encountered error during using sort function

Tags:

python

sorting

I have encountered a problem while using sort function of python.

>>>d = [23,45,67,5,4,23,45,89]
>>>d[5]
23
>>>g = d
>>>g.sort()
>>>d[5]
45

Is there any way, i can get g sorted without disturbing d.

like image 451
Dharmendra Avatar asked Jul 31 '26 08:07

Dharmendra


1 Answers

list.sort sorts in-place, and g = d assigns the reference to the list without copying it. Copy the list as g = d[:] before sorting, or use the built-in function sorted instead:

g = sorted(d)
like image 115
bereal Avatar answered Aug 01 '26 22:08

bereal