Skip to content Skip to sidebar Skip to footer

Sorting A List By Function Leads To Wrong Result

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]],

Solution 1:

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.

deffoo(x):
    y=sorted(x)
    return y
a = [3,2,1]
print(foo(a))

Solution 2:

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]

deffoo1(*x):
    y = sorted(*x)
    print(x, y)
    return y

print(foo1(a))

deffoo2(*x):
    y = sorted(x)
    print(x, y)
    return y

print(foo2(*a))
print(foo2(5, 4, 7, 6))

output

([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]

Note that 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 Unpacking Argument Lists in the official Python tutorial.

Solution 3:

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

deffoo(*x): 
    y=sorted(x[0]) 
    print(y)

Post a Comment for "Sorting A List By Function Leads To Wrong Result"