0

From Python's documentation, I could not understand if arguments are passed by reference or passed by assignment. So, I wrote a simple piece of code to verify it.

def swap(first_number, second_number):
    first_number, second_number = second_number, first_number


if __name__ == '__main__':
    a, b = 4, 5
    swap(a, b)
    print(a, b)

Now, the output is 4, 5 here. After studying a bit, I realized that in swap() function's body, first_number, and second_number are again declared. I could not get around it as I come from a C++ background. So, how do I make the above code work without returning a value?

In C++ I simply write:

void swap_overloaded(unsigned int& first_number, unsigned int &second_number) {
    first_number = first_number ^ second_number;
    second_number = second_number ^ first_number;
    first_number  = first_number ^ second_number;
}

How do I achieve this in python?

Pikachu
  • 304
  • 3
  • 14
  • Python does not support call by reference. It uses call by assignment. See the linked duplicate for what that means. Note, the lack of call by reference means that you can't write a swap function like this. – juanpa.arrivillaga May 14 '20 at 10:44
  • "I realized that in swap() function's body, first_number, and second_number are again declared" No, they aren't. Python *doesn't have variable declarations*. – juanpa.arrivillaga May 14 '20 at 10:45
  • I did answer your question, and I closed it as a duplicate of that other question because it is a straightforward duplicate of "How do I pass a variable by reference?" What is it that you don't understand? – juanpa.arrivillaga May 14 '20 at 10:55
  • @juanpa.arrivillaga So, there is no way that code can work? – Pikachu May 14 '20 at 10:57
  • Yes, **Python does not support call by reference**. Again, what is it that you don't understand? In any case, the swap idiom is trivial in Python, just use it. – juanpa.arrivillaga May 14 '20 at 10:59
  • @juanpa.arrivillaga I am complete new to python – Pikachu May 14 '20 at 11:01

0 Answers0