Home > Programming > Swapping two numbers in Python

Swapping two numbers in Python


Swapping two numbers in Python is damn easy. It doesn’t require another temporary variable or complicated assignments if the swapping to be done with in one line.

Swapping of two numbers in C with in one line Here

Swapping of two numbers in C using Bitwise operators Here

Both of the above programs do not require the additional temporary variable but I have to say, they are some what complicated but in case of Python just one assignment. Take a look at the below code

def swap(a,b):
	print 'Before swapping a=%s b=%s' %(a,b)
	a,b=b,a
	print 'Before swapping a=%s b=%s' %(a,b)

def main() :
	a=raw_input("Enter a:")
	b=raw_input("Enter b:")
	swap(a,b)

if __name__=='__main__' :
	main()
Advertisements
  1. Bob
    July 1, 2012 at 6:00 pm

    Indeed python makes swapping easy by assigning tuples. But your function will not swap the values in main. With this main and your swap() The output shows that the swap happened in the function, but not in data main.

    def main() :
    a=”foo”
    b=”bar”
    print ( (a,b) )
    swap(a,b)
    print ( (a,b) )

    —- ouput —-
    (‘foo’, ‘bar’)
    Before swapping a=foo b=bar
    Before swapping a=bar b=foo
    (‘foo’, ‘bar’)

    I needed a swap that kept track of how many times it was called. So I did this:

    def swap(pair):
    # counting code here
    return (pair[1],pair[0])

    the when you call swap you have to say:

    (a,b) = swap( (a,b) )

  1. August 31, 2011 at 9:32 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: