+ 1

how to swap two variables in a function

like in c we have to pass the arguments by reference is there a way in python too

4th Jan 2017, 4:29 PM
Raman Shukla
Raman Shukla - avatar
10 Respostas
+ 3
Inside a body, use: a, b = b, a. No matter the type of the variables. You cannot (as far as I know) use a function to swap to values of variables, however. (at least without any return and assignment) But that way is far simple and faster than using temporary variables. It might be possible, but I don't know about any such way and I think this is far superior.
4th Jan 2017, 11:46 PM
Amaras A
Amaras A - avatar
+ 2
(in python) This sort of swap function works only for mutable types (list, set...). So in your case you would have to wrap the values in a list or object.
4th Jan 2017, 5:16 PM
ifl
ifl - avatar
+ 1
int a=1,b=2; int c;//temporary variable c=a; a=b; b=c; //swapped
4th Jan 2017, 4:43 PM
Nawaj Shareef
Nawaj Shareef - avatar
+ 1
@raman Shukla , use that code in function, it is not a askable question, try yourself.
4th Jan 2017, 4:48 PM
Nawaj Shareef
Nawaj Shareef - avatar
+ 1
No, I don't know Python, and no need of Python. in every language, logic is same and algorithms are same. if you can not implement this code in your best langauge......
4th Jan 2017, 4:52 PM
Nawaj Shareef
Nawaj Shareef - avatar
0
i know swapping i meant in function def swap(x,y): temp =x x=y y=temp a=5 b=10 swap(a,b) //not swapped
4th Jan 2017, 4:46 PM
Raman Shukla
Raman Shukla - avatar
0
do u know python buddy if yes then try writing your code with function and we will see
4th Jan 2017, 4:50 PM
Raman Shukla
Raman Shukla - avatar
0
if u read my question carefully leaving your arrogance behind u will see that i have already mentioned c and i m also talking about through function call not just simply swap i know swapping in c
4th Jan 2017, 4:56 PM
Raman Shukla
Raman Shukla - avatar
0
thanx guys for answering so fast.... this is the answer i wanted (unlike some people who doesn't read the question properly ) thank you very much @ifl good one pointing that out i have tried lists though thanx @Amaras A thanx buddy although i was asking this question not for swapping primarily.... swapping was secondary.... i wanted the changes in functions to be retained
5th Jan 2017, 12:55 PM
Raman Shukla
Raman Shukla - avatar
0
After reading @ifl's answer, I agree with them: you have to wrap them inside a list and swap the interior of the list
5th Jan 2017, 4:12 PM
Amaras A
Amaras A - avatar