Swapping values

0 votes

I have seen this code used to swap the values of two variables -

a, b = b, a

How does this work?

Jun 8, 2018 in Python by nightshade
• 870 points

recategorized Jun 11, 2018 by Sudhir 11 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
0 votes
a,b = b,a

Here, python interprets the comma separated variables as tuples. The RHS is first evaluated as a tuple and then stored in memory. The LHS is then evaluated as a tuple and is assigned the values of the RHS. Hence, the net effect is that the values of the variables are swapped.

answered Jun 8, 2018 by Hamartia's Mask
• 1,580 points

Related Questions In Python

+2 votes
2 answers

How can I replace values with 'none' in a dataframe using pandas

Actually in later versions of pandas this ...READ MORE

answered Aug 13, 2018 in Python by bug_seeker
• 14,970 points
2,464 views
0 votes
1 answer

Looping over dictionary values

You can loop over the dictionary and ...READ MORE

answered Apr 17, 2018 in Python by Nietzsche's daemon
• 4,260 points
14 views
0 votes
1 answer

Returning values in python

Place your values in a tuple and ...READ MORE

answered Apr 26, 2018 in Python by Nietzsche's daemon
• 4,260 points
10 views
0 votes
1 answer

How to replace values with None in Pandas data frame in Python?

Actually in later versions of pandas this ...READ MORE

answered Aug 30, 2018 in Python by Priyaj
• 56,120 points
282 views
0 votes
1 answer

How to Parse values from a JSON file?

import json from pprint import pprint with open('data.json') as ...READ MORE

answered Oct 15, 2018 in Python by Priyaj
• 56,120 points
32 views
0 votes
1 answer

Array values in Python

You can use the enumerate function and ...READ MORE

answered Nov 28, 2018 in Python by SDeb
• 9,660 points
18 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
22 views
+4 votes
6 answers

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.