简体   繁体   中英

Python referring to an item in a list from another list

I have a list of variables (listA) from from another list (listB). The problem I am having is that the items from listB are being passed by value to listA rather than by reference. Is there anyway I can access the the object in listB after having put its value in listA?

For example:

listB = [1,2,3,4,5]
listA = [listB[0], listB[1]]
listA[0] = 0

this makes listA equal to [0, 2], and leaves listB unchanged. I would like to modify listB so that it becomes [0,2,3,4,5].

I have of course come up with a solution to this, but its ugly, and I was wondering if there was an elegant way of doing this.

Everything in python is a reference. After all those statements are executed, listB[1] and listA[1] are literally the same object. (you can check, by calling id(listB[1]) and id(listA[1]) .

The reason listA[0] and listB[0] are different is merely because you put a different reference into that spot.

Judging from your description, you don't want to a listA that stores references to the objects in listB . What you want is a listA that is a view of listB . I believe you have only two options:

  • Create a special sequence that internally stores a reference to listA , and whose __getitem__ and __setitem__ methods perform lookups into listA when invoked.

  • Create special a special reference types that contains something like a "sequence and index". Put these references into listA . But, to modify listB through listA , you'll have to invoke some sort of "get" and "set" members of these reference objects.

You can't. First of all integers are immutable and they don't work like integers in C/C++. You can't get pointer/reference to an integer and then change it (I mean you can, you always have a reference, but it is usually reference to a single object; check this x = 1; y = 1; print id(x), id(y) ; id values should be the same and they are memory addresses). What you can do is get index of elements in listB and change the list, eg:

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

But probably you are trying to do something you are not supposed to do, because Python works differently than C++. What are you trying to achieve?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM