+ 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
10 Réponses
+ 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.
+ 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.
+ 1
int a=1,b=2;
int c;//temporary variable
c=a;
a=b;
b=c;
//swapped
+ 1
@raman Shukla , use that code in function, it is not a askable question, try yourself.
+ 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......
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
0
do u know python buddy
if yes then try writing your code with function and we will see
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
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
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