Python - Multiple Assignment [duplicate] - python

This question already has answers here:
Multiple assignment and evaluation order in Python
(11 answers)
Closed 2 years ago.
Recently I was reading through the official Python documentation when I came across the example on how to code the Fibonacci series as follows:
a, b = 0, 1
while a < 10:
print (a)
a, b = b, a + b
which outputs to 0,1,1,2,3,5,8
Since I've never used multiple assignment myself, I decided to hop into Visual Studio to figure out how it worked. I noticed that if I changed the notation to...
a = 0
b = 1
while a < 10:
print (a)
a, b = b, a + b
... the output remains the same.
However, if I change the notation to...
a = 0
b = 1
while a < 10:
print(a)
a = b
b = a + b
... the output changes to 0, 1, 2, 4, 8
The way I understand multiple assignments is that it shrinks what can be done into two lines into one. But obviously, this reasoning must be flawed if I can't apply this logic to the variables under the print(a) command.
It would be much appreciated if someone could explain why this is/what is wrong with my reasoning.

a = 0
b = 1
while a < 10:
print(a)
a = b
b = a + b
In this case, a becomes b and then b becomes the changed a + b
a, b = 0, 1
while a < 10:
print (a)
a, b = b, a+b
In this case, a becomes b and at the same time b becomes the original a + b.
That's why, in your case b becomes the new a + b, which, since a = b, basically means b = b + b. That's why the value of b doubles everytime.

When you do a, b = d, e the order in which assignment happens in from right to left. That is, b is first given the value of e and then the other assignment happens. So when you do a, b = b, a + b what you are effectively writing is,
b = a + b
a = b
Hence the difference.
You can verify this by doing
a = 0
b = 1
while a < 10:
a, b = b, a + b
print(a, b)
the first output is 1 1. So first b becomes 0+1 and then a is given the value of b=a making it also 1.
If you want more details on how this works, you can check out this question.

In a multiple assignment, the right side is always computed first.
In effect,
a, b = b, a + b
is the same as:
b = a + b
a = b

Related

Different output than expected

I just started programming and right now I'm stuck with a problem. I'm wondering how if functions really work.
a = [ 20.0, 8.0, 2.5 ]
b = 4
if b > len(a):
r = 2*b
r = b
I expected the output of 8, but the actual output is 4. How come? Because 4 > 3 and that should execute the if statement right?
The problem is that you do not have an else statement which should be executed if your condition if b > len(a) is not True. So in your code, the if statement is first executed, the value of r becomes twice of b (r becomes 8) but then you come out of the if statement and again reassign b to r which is why your r becomes 4 again. I hope the concept is clear now.
The correct way would be
a = [ 20.0, 8.0, 2.5 ]
b = 4
if b > len(a):
r = 2*b
else:
r = b

Explain how multiple variable assignment in single line works? (Example: a, b = b, a+b)

Say I have this Python code
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
For n=1000 this prints:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
But I don't understand why it's 1 1 2 3.
The issue is with this line:
a, b = b, a+b
What is the order of execution?
The two options I see are:
1:
a = b
b = a+b
2:
b = a+b
a = b
But neither gives me the correct result when I try it manually.
What am I missing?
None of the two options you shared actually describe the working of:
a, b = b, a+b
Above code assigns a with the value of b. And b with the older value of a+b (i.e. in a+b the older value of a). You may consider it as an equivalent of:
>>> temp_a, temp_b = a, b
>>> a = temp_b
>>> b = temp_a + temp_b
Example: Dual variable assignment in one line:
>>> a, b = 3, 5
>>> a, b = b, a+b
>>> a
5
>>> b
8
Equivalent Explicit Logic:
>>> a, b = 3, 5
>>> temp_a, temp_b = a, b
>>> a = temp_b
>>> b = temp_a + temp_b
>>> a
5
>>> b
8
The order of operations in a, b = b, a+b is that the tuple (b, a+b) is constructed, and then that tuple is assigned to the variables (a, b). In other words, the right side of the assignment is entirely evaluated before the left side.
(Actually, starting with Python 2.6, no tuple is actually constructed in cases like this with up to 3 variables - a more efficient series of bytecode operations gets substituted. But this is, by design, not a change that has any observable differences.)
It's python standard way to swap two variables, Here is a working example to clear your doubt,
Python evaluates expressions from left to right. Notice that while
evaluating an assignment, the right-hand side is evaluated before the
left-hand side.
http://docs.python.org/3/reference/expressions.html#evaluation-order
a=[1,2,3,4,5]
for i,j in enumerate(a):
if i==1:
a[i-1],a[i]=a[i],a[i-1]
print(a)
output:
[1, 2, 3, 4, 5]
For more info , read this tutorial

numpy dot product but keep as vector (not add elements up)

I want something like the following:
a = b 'dot' c x h'
where
a is 10 by 201
b = 10 by 1
c = 10 by 1
h is 1 by 201
However, when I say b 'dot' c, I don't actually want to sum everything up to get a scalar -I want a 10 by 1 vector as the result.
I don't know what this actually is.
np.dot(b, c) doesn't work because it computes the dot product scalar.
a = b * c * h should work. It's an example of broadcasting.

How to add to an already existing variable in python?

I know this is a very simple question, but I couldn't find it. Basically what I'm trying to is have a=2, b=3, and I need a+b=b so when I add a and b what it equals needs to be b.
Either:
b = a + b
# make b equal to a + b
Or
b += a
# increase the value of b by a
declare variables
a = 2
b = 3
operates
b = a+b
You can use the += shorthand for summation on variable.
For instance, in order to add in the value of a in the b variable, and retaining the last value of b:
b += a
This is the same thing as saying: b = a + b. Both works fine. Choose as you feel is readable.
Here is a quick example:
First, initialize your variables:
a = 2
b = 3
print a, b
Output: 2 3
You can add a to b, this way:
b += a
print b
Output: 5
You can also add to the actual value of b 10
b = 10+b
print b
Output: 15

Pythonic way to do conditionally assign variables

Any suggestions on how to do that in Python?
if x():
a = 20
b = 10
else:
a = 10
b = 20
I can swap them as below, but it's not as clear (nor very pythonic IMO)
a = 10
b = 20
if x():
[a, b] = [b, a]
(a,b) = (20,10) if x() else (10,20)
Swapping values with a, b = b, a is considered idiomatic in Python.
a, b = 10, 20
if x(): a, b = b, a
One nice thing is about this is you do not repeat the 10 and 20, so it is a little DRY-er.

Categories

Resources