Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I want to know the difference between the following Python expressions:

# First:

a,b = b,a+b

# Second:

a = b

b = a+b

First gives different results than Second.

e.g.,

First:

>>> a = 1

>>> b = 2

>>> a,b = b,a+b

>>> a

2

>>> b

3

Second:

>>> a = 1

>>> b = 2

>>> a = b

>>> b = a+b

>>> a

2

>>> b

4

I want to know why I am getting 3 in First and 4 in Second?

1 Answer

0 votes
by (107k points)

Kindly be informed that in an assignment declaration, the right-hand side is constantly evaluated fully before doing the actual setting of variables. So if you do,

x, y = y, x + y

This will evaluates y, and x + y, then sets x to ham and y to spam. I.e., it's like

ham = y

spam = x + y

x = ham

y = spam

By contrast,

x = y

y = x + y

sets x to y, then sets y to x (which == y) plus y, therefore it is same as:

x = y

y = y + y

Want to get certified in Python? Register for this complete Python Training course by Intellipaat. 

Related questions

0 votes
1 answer
0 votes
1 answer
asked Dec 27, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
0 votes
4 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...