How to Swap Two Variables using Python?


By using a temporary variable −

>>> x=10
>>> y=20
>>> z=x
>>> x=y
>>> y=z
>>> x,y
(20, 10)

Without using temporary variable

>>> a,b=5,7
>>> a,b
(5, 7)
>>> a,b=b,a
>>> a,b
(7, 5)

Updated on: 02-Mar-2020

269 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements