LaPXL8R
LaPXL8R

Reputation: 39

Copying element from one list to another in python

Let's say that I created two different lists:

listA = [0, 0, 0]
listB = [1, 1, 1]

I want to make the an element in listB refer to the same object as an element in listA. So that the element in both lists change together.

listB[2] = listA[0]
>>listB[2]
>>0

listB[2] = 2
>>listA[0]
>>2

However doing the above just passes the value of the elements, so the lists are still referring to individual objects. Is there a method or a different data structure that could give me the desired effect?

Upvotes: 0

Views: 2598

Answers (2)

BrenBarn
BrenBarn

Reputation: 251355

You can't do that. You can either make listA and listB themselves be the same object, in which case all their indices will reflect any changes made to either, or you can make them separate objects, in which case none of their indices will reflect changes. You can't make two lists that are "joined at the hip", sharing only some of their index references.

Suppose that the value of listB[2] is some object called obj. When you do something like listB[2] = 2, you aren't changing obj; you are changing listB (by making its index 2 point to some other object). So you can't make listA[2] "reflect" listB[2] unless listA and listB are the same object. You can certainly make listA[2] and listB[2] refer to the same object, but that won't affect what happens when you do listB[2] = 2, because that operation won't affect that shared object at all.

Upvotes: 1

Alex Hall
Alex Hall

Reputation: 36013

Here's a simple idea to get you started, and also help you understand better what's going on:

>>> listA = [[0], [0], [0]]
>>> listB = [[1], [1], [1]]
>>> listA[0] = listB[0]
>>> listA
[[1], [0], [0]]
>>> listB[0][0] = 2
>>> listB
[[2], [1], [1]]
>>> listA
[[2], [0], [0]]

But be careful:

>>> listB[0] = [3]
>>> listB
[[3], [1], [1]]
>>> listA
[[2], [0], [0]]

You could write a class that makes this invisible so it looks more like a list and is easier to use without making mistakes.

Upvotes: 1

Related Questions