user1676273
user1676273

Reputation: 29

simple swap in python, conceptual confusion

So I've already graduated and received all credits for my compsci degree. But my professor from my last quarter just sent me an email saying he found something interesting in one of my homework assignments. I forget the context, but I don't think it matters. I'll post the email exchange.


From: PROF
To: ME
Subject: RE: LDA

Hi STUDENT,
I noticed something odd in one of your homework answers:

def swap(i,j):
    tmp = i
    i = j
    j = tmp
    return i,j

This works, but what is wrong with it?


From: ME
To: PROF
Subject: RE: LDA

oh yea, I was thinking in C, wouldn't it work in python to do:

def swap(i,j): 
    i,j = j,i
    return i,j

Python will then optimize that swap on the stack eliminating the need for an tmp variable at all.


From: PROF
To: ME
Subject: RE: LDA

that's true, but there is a more subtle conceptual confusion

So my question is: what am I missing here?

Upvotes: 0

Views: 608

Answers (4)

Daniel Roseman
Daniel Roseman

Reputation: 599610

I guess his point is that inside a function there's no need to do the swap at all - because the return values of the function aren't tied to the values passed in, so this would do as well:

def swap(i, j):
    return j, i

So in fact there's no point in having the function, it doesn't add anything at all. You'd have to call i, j = swap(i, j) - which is exactly the same as j, i = i, j.

Upvotes: 0

Preet Kukreti
Preet Kukreti

Reputation: 8607

All he was expecting was the pythonic way to swap:

i, j = j, i

Upvotes: 1

Michael
Michael

Reputation: 11

Your function seems overcomplicated, surely you could just do this

def swap(i,j): return j,i

This would achieve the same thing with only one line of code?

Upvotes: 1

nneonneo
nneonneo

Reputation: 179422

Think about how you would call swap in Python, versus how you would call a swap function in C.

For example, in C,

swap(&a, &b);

is valid and swaps the memory in a with the memory in b (assuming the implementation of swap is right).

But, in Python,

swap(a, b)

...does nothing! You'd have to assign the result:

a,b = swap(a,b)

but then why don't you just do

a,b = b,a

and ditch the swap() function completely?

If you really understand the difference between Python and C, you will be able to explain why the Python swap function cannot swap two variables without assigning the result.

Upvotes: 7

Related Questions