0

How can I create a pair of iterables containing the same items (not just copies, but shared memory of items) but in different order, and such that a change to an item in one of the iterables will be reflected in the other iterable?

For example:

>>> x = [0, 1, 2, 3] >>> y = [x[1], x[2], x[3], x[0]] >>> x[2] is y[1] True 

Great so far, but if I make a change to one of the items in an iterable, it ends up creating a new item (new memory) space, not changing the item in that same memory space.

>>> x[2] *= 5 >>> x[2] is y[1] False >>> x[2] 10 >>> y[1] 2 

1 Answer 1

1

Put each item in a box:

>>> x = [[0], [1], [2], [3]] >>> y = [x[1], x[2], x[3], x[0]] >>> x[2] is y[1] True >>> x[2][0] *= 5 >>> x[2] is y[1] True >>> x[2] [10] >>> y[1] [10] 

Here I'm using a list, but any mutable container will do.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, @Samwise! I had tried something like that before, but with this line instead: x[2] = [x[2][0]*5]. Now I see why that failed. I was creating a new list (what I'll think of unofficially from now on as a "container") rather than replacing the 0th item in the existing list. Great!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.