I have a list :
L=[2,0,4,5]
and I want to create a new list without changing L itself:
K= [0,2,4,5]
but when I try:
K=L.sort()
print(K)
it prints nothing, and if I try:
print(L)
it comes out : [0,2,4,5]
why K is not =[0,2,4,5]? and how can I make a new list [0,2,4,5] and don't change L?
To create a completely independent copy of a list, use the copy module's deepcopy() function.
If you want to create a new sorted list without modifying the original one, you should use the sorted function instead. As you can notice, both sort and sorted sort items in an ascending order by default.
The items in the outer list are List<int> objects. In the first line, you create the outer list. In the second line, you create a list of int and add it as one of the items in the outer list. In the third line, you add an integer to the first inner list in the outer list.
The following will make a sorted copy of L
and assign it to K
:
K = sorted(L)
sorted()
is a builtin function.
The reason K = L.sort()
doesn't work is that sort()
sorts the list in place, and returns None
. This is why L
ends up being modified and K
ends up being None
.
Here is how you could use sort()
:
K = L[:] # make a copy
K.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