Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create new list without changing the original list

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?

like image 716
user1817310 Avatar asked Nov 26 '12 21:11

user1817310


People also ask

How do I create an independent copy of a list?

To create a completely independent copy of a list, use the copy module's deepcopy() function.

How do you sort a list without changing the original list Python?

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.

Can we create a list inside another list?

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.


1 Answers

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()
like image 93
NPE Avatar answered Sep 22 '22 16:09

NPE