0

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?

Umutambyi Gad
  • 4,082
  • 3
  • 18
  • 39
Asker123
  • 350
  • 1
  • 3
  • 15

3 Answers3

0

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

Umutambyi Gad
  • 4,082
  • 3
  • 18
  • 39
0

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
yoav
  • 324
  • 4
  • 22
  • There is https://pypi.org/project/mutableint/ which does essentially this, except that you can also use it in arithmetic etc. – alani Jul 04 '20 at 22:24
0

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.