Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When adding to list why does Python copy values instead of pointers?

What I was trying to do (C code):

int a = 2, b = 3, c = 4;

int* arr[3] = {&a, &b, &c};

for (int i = 0; i < 3; ++i) {
    if (*(arr[i]) > 1) {
        *(arr[i]) = 1
    }
}

I was expecting Python to do similar pointer like behavior with this piece of code.

>>> a = 2
>>> b = 3
>>> c = 4
>>> for x in [a, b, c]:
...     if x > 1:
...             x = 1
... 
>>> a,b,c
(2, 3, 4)

How can the C code like behavior be achieved in Python?

like image 831
juke Avatar asked Dec 02 '25 08:12

juke


2 Answers

Python doesn't have pointers in that sense.

Python variables are names bound to a value not a location in memory, so changing the value for one variable does not change the value for another variable with the same value.

You can achieve something a bit like you want using locals:

>>> a = 2
>>> b = 3
>>> c = 4
>>> for x in 'a','b','c':
...    if locals()[x] > 1:
...       locals()[x] = 1
... 
>>> a
1

However, I'd strongly recommend against doing this. If you post another question explaining the problem you're try to solve you'll get a more "Pythonic" way of doing it.

It may just be a case of storing your values in a dict:

>>> vals = { 'a' : 2, 'b' : '3', 'c' : 4 }
>>> for key,value in vals.items():
...     if value > 1:
...        vals[key] = 1
... 
>>> vals
{'a': 1, 'c': 1, 'b': 1}
like image 75
Dave Webb Avatar answered Dec 03 '25 23:12

Dave Webb


You should use mutable objects for that.
For example:

a = 2
b = 3
c = 4

ls = [a, b, c]

for i, val in enumerate(ls):
     if val > 1:
        ls[i] = 1

print ls

gives you:

[1, 1, 1]

if you need a, b, c:

>>> [a, b, c] = ls
>>> a
1
like image 25
joaquin Avatar answered Dec 03 '25 22:12

joaquin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!