Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which python data types act like pointers?

Tags:

python

types

For example, the dictionary below updates for changes in the list but not for the int.

What is the name of the property of the data type that tells me if it will act like the int or like the list in this example?

How do I set this property when building classes?

Is there a way to make the "i" variable in my example behave like the "l" variable?

i = 1
l = [1]

d = {'i':i,'l':l}
i = 0
l[0] = 0
print(d) # {'i': 1, 'l': [0]}
like image 973
Charles Fox Avatar asked Jun 22 '26 17:06

Charles Fox


1 Answers

Python passes things around by assignment, so basically Python always passes a reference to the object, but the reference is passed by value.

An example where the value of the reference is not changed:

def foo(list_):
    list_.append(0)

l = [3, 2, 1]
foo(l)
# l = [3, 2, 1, 0]

Now one where it is changed:

def foo(list_):
    list_ = [1, 2, 3]

l = [3, 2, 1]
foo(l)
# l = [1, 2, 3]

You could also get a copy of the list:

def foo(list_):
    list_copy = list_.copy()
    list_copy.append(0)

l = [3, 2, 1]
foo(l)
# l = [3, 2, 1]

In your example you changed the value of the reference of the i variable inside the dict d, but not of the list l, you used the reference and changed an item inside the list. This happened because lists are mutable, Python integers are not, you made two different operations. You won't be able to change what is inside the dict d using the variable i after the assignment, you would need to do d['i'] = 0 for that.

like image 141
Vitor Falcão Avatar answered Jun 25 '26 05:06

Vitor Falcão



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!