Grr Grr - 3 months ago 5
Python Question

modifying argument value within function

I am trying to figure out a way to modify the order of a list of tuples within a function without returning the list.

For example:

L = [(2,4),(8,5),(1,3),(9,4)]
def sort_ratios(L):
L = sorted(L, key=lambda x: float(x[0])/float(x[1]))
return L


Thus, calling sort_ratios() outputs:

>>>sort_ratios(L)
[(1,3),(2,4),(8,5),(9,4)]


But
L
would still be
[(2,4),(8,5),(1,3),(9,4)]

Instead, I would like to simply modify the value of L without returning anything so that
sort_ratios()
operates as follows:

>>>sort_ratios(L)
>>>L
[(1,3),(2,4),(8,5),(9,4)]


It seems trivial, but I just can't seem to get the function to operate this way.

Answer

Try L.sort(key=lambda x: float(x[0])/float(x[1])) for an in-place sort.