Exchange two lists in python

I have a list of 2 lists with the same size in python, for example:

list_of_lists = [list1, list2] 

In the for loop, after doing some processing on both list1 and list2 I have to swap them so that list1 becomes list2 and list2 becomes a list initialized with all zeros. Therefore, at the end of the iteration, list_of_lists should look like this:

 list_of_lists = [list1 which has contents of list2, list2 which has all zeros] 

In C, you can simply copy the pointers list2 and list1 , and then point list2 to a list initialized to all zeros. How to do this in python?

+4
source share
3 answers

It looks like you work mainly with list1 and list2 inside a loop. Therefore, you can simply reassign their values:

 list1 = list2 list2 = [0]*len(list2) 

Python also allows you to shorten this to a single line:

 list1, list2 = list2, [0]*len(list2) 

but in this case, I think the two-line version is more readable. Or, if you really want list_of_lists , then:

 list_of_lists = [list2, [0]*len(list2)] 

or if you want:

 list1, list2 = list_of_lists = [list2, [0]*len(list2)] 
+9
source

Like this...

 list_of_lists = [list_of_lists[1], []] for i in range(count): list_of_lists[1].append(0) 
+1
source
 list_of_lists=[ list_of_lists[1], [0,]*len(list_of_lists[1] ] 

The cost of the swap is the same as the pointer you specified

+1
source

All Articles