4

I have a list of 2 lists, which are of equal size, in python like:

list_of_lists = [list1, list2]

In a 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 to all zeros. So at the end of the iteration the list_of_lists has to look like:

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

In C, one could just copy the pointers of list2 and list1 and then point list2 to a list initialized to all zeros. How do I do this in python ?

3 Answers 3

9

It sounds like you are mainly working with list1 and list2 inside the loop. So you could just reassign their values:

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

Python also allows you to shorten this to a one-liner:

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

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

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

or if you want both:

list1, list2 = list_of_lists = [list2, [0]*len(list2)]
Sign up to request clarification or add additional context in comments.

Comments

1

Like this...

list_of_lists = [list_of_lists[1], []]

for i in range(count):
    list_of_lists[1].append(0)

Comments

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.