For example
b = 4
c = []
c.append(b)
print(c)
b += 2
print(c)
I was hoping I would get
4
6
but I got
4
4
Any chance I could add the element as a pointer. And then if I reference that element with c[0] I'd be referencing the b?
For example
b = 4
c = []
c.append(b)
print(c)
b += 2
print(c)
I was hoping I would get
4
6
but I got
4
4
Any chance I could add the element as a pointer. And then if I reference that element with c[0] I'd be referencing the b?
here c
and b
are different variables where c
is list and b
is int so if you add some on b
it doesn't mean and c
will be updated but if you add some number on b
and append it again on c
there will be a change
b = 4
c = []
c.append(b)
print(c)
b += 2
c.append(c)
print(c)
and what you will get is
[4, 6]
and I think is clear that a c
didn't change in your question
You can do that with a class:
class Number:
def __init__(self, number):
self.number = int(number)
def __str__(self):
return str(self.number)
def __repr__(self):
return self.__str__()
def __add__(self, other):
self.number = self.number + other
b = Number(4)
c = []
c.append(b)
print(c)
b += 2
print(c)
You will get:
4
6
Refer this below link to understand how the reference works in python: How do I pass a variable by reference?
So, in short,
python objects i.e. booleans
, integers
, floats
, strings
, and tuples
are immutable, which means that after you create the object and assign some value to it, you can't modify that value.
Hence, when you do b += 2
, here, b
will point to a new memory reference.
Proof:
>>> b=10
>>> id(b)
1734146112
>>> b+=2
>>> id(b)
1734146144
>>>
However, as @yoav mentioned above,
you can also do this by tweaking the default behaviour of Number
class but beware; you should use it very carefully as you might not need this behaviour for every class.