If you're familiar with C++, then think of arguments in Python as "references passed by value". That is, you're not receiving a copy of the object so if it's mutable then you can modify what's passed in (though this is generally discouraged) although you cannot reassign the variable that was passed in to a different object. Really, C++ needs to be able to do that because there's no good way to return multiple values. In Python, you can just return a (potentially implicit) tuple, and just as easily "unpack" that tuple. Take this example
- Code: Select all
>>> from math import sqrt
>>> def square_and_sqrt(x):
return x**2, sqrt(x)
>>> bigger, smaller = square_and_sqrt(9)
I've noticed this same thing in some Java code at work recently. We created empty lists and passed them into a function to populate them, because Java lacks a nice way to simply return them at the same time from the same function. Python does not have this limitation or require "side effects" of functions to achieve the same result.