Storing elements of one list, in another list - by reference - in Python?

2024/11/13 9:31:02

I just thought I'd jot this down now that I've seen it - it would be nice to get a confirmation on this behavior; I did see How do I pass a variable by reference?, but I'm not sure how to interpret it in this context.

Let's say we have these two arrays/lists:

a = [1, 2, 3, 4]
b = [-1, a, -100, a[2], -1]

The interpreter initially sees them as:

>>> print(a)
[1, 2, 3, 4]
>>> print(b)
[-1, [1, 2, 3, 4], -100, 3, -1]

Now let's change a[2], and see what happens:

>>> print(a)
[1, 2, 55, 4]
>>> print(b)
[-1, [1, 2, 55, 4], -100, 3, -1]

So, wherever list b has a reference to the list a, the value has been updated - but wherever b was initialized with (a reference to?) an element from list a, it seems that Python expanded the value at initialization time, and thus stored the element by value (not by reference), so it's value obviously doesn't update.

Basically, I found a use case, where it would be convenient to be able to define e.g. b = [-1 a[2] -1], and then update a[2], and be able to count that the latest value of a[2] will be emitted when getting the value of (in this case) b[1]. Is there a way to do that in Python, without having to do b = [-1 a -1], and then reading b[1][2] (I'd like to get the value of a[2] just by using b[1])?

Answer

a is a reference to a mutable list. So, when you say:

a[2] = 55

you are calling __setitem__ on the list which sets an item in the list. list.__setitem__ doesn't make any attempt to mutate the item that used to be stored in the second index. It simply replaces that reference with a new one.

On the other side, x = a[2] calls __getitem__ which just creates a new reference to the object stored at that index in the list.

https://en.xdnf.cn/q/72347.html

Related Q&A

Joining Two Different Dataframes on Timestamp

Say I have two dataframes:df1: df2: +-------------------+----+ +-------------------+-----+ | Timestamp |data| | Timestamp |stuff| +-------------------+---…

Find if the array contain a 2 next to a 2

I am stuck on this problemGiven an array of ints, return True if the array contains a 2 next to a 2 somewhere.has22([1, 2, 2]) → True has22([1, 2, 1, 2]) → False has22([2, 1, 2]) → FalseI know the b…

AttributeError: xml.etree.ElementTree.Element object has no attribute encode

Im trying to make a desktop notifier, and for that Im scraping news from a site. When I run the program, I get the following error.news[child.tag] = child.encode(utf8) AttributeError: xml.etree.Element…

How to parse code (in Python)?

I need to parse some special data structures. They are in some somewhat-like-C format that looks roughly like this:Group("GroupName") {/* C-Style comment */Group("AnotherGroupName")…

Using OpenCV detectMultiScale to find my face

Im pretty sure I have the general theme correct, but Im not finding any faces. My code reads from c=cv2.VideoCapture(0), i.e. the computers videocamera. I then have the following set up to yield where …

Get marginal effects for sklearn logistic regression

I want to get the marginal effects of a logistic regression from a sklearn modelI know you can get these for a statsmodel logistic regression using .get_margeff(). Is there nothing for sklearn? I want…

How to use win32com.client.constants with MS Word?

Whats wrong with this code? Why win32com.client.constants doesnt have attribute wdWindowStateMinimize?>>> import win32com.client >>> w=win32com.client.Dispatch("Word.Applicatio…

How to properly patch boto3 calls in unit test

Im new to Python unit testing, and I want to mock calls to the boto3 3rd party library. Heres my stripped down code:real_code.py:import boto3def temp_get_variable(var_name):return boto3.client(ssm).ge…

import a github into jupyter notebook directly?

Hey Im creating a jupyter notebook, would like to install: https://github.com/voice32/stock_market_indicators/blob/master/indicators.py which is a python program not sure how to do it directly so anybo…

Django : Call a method only once when the django starts up

I want to initialize some variables (from the database) when Django starts. I am able to get the data from the database but the problem is how should I call the initialize method . And this should be o…