0

Entering the following code into Python 3.5 shell gives me an answer I didn't expect, very basic I know but would somebody help me with an explanation please.

>>> x = 5
>>> y = 2
>>> a = x*y
>>> x,y,a
(5, 2, 10)

>>> x = 3
>>> x,y,a
(3, 2, 10)

These were all on separate lines each preceded by >>>

I expected 6, but the "new" x has not been used.

Georgy
  • 12,464
  • 7
  • 65
  • 73
hal_v
  • 153
  • 1
  • 7
  • Possible duplicate of [Python assigning multiple variables to same value? list behavior](https://stackoverflow.com/questions/16348815/python-assigning-multiple-variables-to-same-value-list-behavior) – vaultah Sep 23 '17 at 01:00
  • Or [python variables are pointers](https://stackoverflow.com/q/13530998/2301450). Or [Why variable = object doesn't work like variable = number](https://stackoverflow.com/q/29926485/2301450). – vaultah Sep 23 '17 at 01:08
  • Does this answer your question? [Are python variables pointers? or else what are they?](https://stackoverflow.com/questions/13530998/are-python-variables-pointers-or-else-what-are-they) – Georgy May 27 '20 at 13:01

4 Answers4

2

a = x*y isn't an equation that automatically updates a whenever you change x or y. It sets a to x*y once when the statement is run. Any changes to x or y afterward have no effect on a.

You'll need to manually update a when you change x or y, or, if the situation allows it, use local functions to do what @Silvio's answer shows. It's handy to create local shortcuts to help clean up code.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
2

The 'a' variable will only be updated if you update it deliberately. In order to update 'a' after you have changed 'x', you will need to execute the line a = x*y again.

If you copy and paste your code into here http://www.pythontutor.com/visualize.html#mode=edit it will give you a good visualization of what is going on!

1

When you assign a, the value is set then and there.

a = x * y

The current values of x and y are used. The expression x * y isn't stored anywhere, so Python can't possibly know to update it. If you want a value that automatically updates based on the values of its variables, you can use a closure.

x = 5
y = 2
a = lambda: x * y
print(x, y, a()) # Prints 5 2 10
x = 3
print(x, y, a()) # Prints 3 2 6

This ensures that the expression is evaluated every time a is called.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
0

a variable won't be updated. You may want to create a function this way

def a(x,y):
    return x*y

And then you can create the tuple

(x, y, a(x,y))