When passing a list as an argument in function, why is the following list not changed?
def foo(*x): y=sorted(x) print(y) a=[3,2,1]
The function is returning
[[3, 2, 1]], not
[[1,2,3]]. Why is this happening? Is this something to do with call by value?
Why creating another function? You can just do this
>>> a = [3,2,1] >>> sorted(a) [1, 2, 3]
However if you want to create another function. You have to call it.
def foo(x): y=sorted(x) return y a = [3,2,1] print(foo(a))Answer2:
As Blue Monday says, there's no need to create a new function for this, you should just call the
sorted function. However, here are a couple of other ways to fix your code.
a = [3, 2, 1] def foo1(*x): y = sorted(*x) print(x, y) return y print(foo1(a)) def foo2(*x): y = sorted(x) print(x, y) return y print(foo2(*a)) print(foo2(5, 4, 7, 6))
([3, 2, 1],) [1, 2, 3] [1, 2, 3] (3, 2, 1) [1, 2, 3] [1, 2, 3] (5, 4, 7, 6) [4, 5, 6, 7] [4, 5, 6, 7]
foo2 expects us to pass in the items to sort as individual arguments. We can pass it a list (or tuple) by using the
* "splat" operator in the function call. See <a href="https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists" rel="nofollow">Unpacking Argument Lists</a> in the official Python tutorial.
because the argument of your function is specified as *a, which is like saying your argument is a tuple of undefined dimension
when you try to sort a tuple with a nested list, the value will not change
infact as result you got a list of list (you got [[3, 2, 1]] not [3, 2, 1])
if you try this, it will work
def foo(*x): y=sorted(x) print(y)