Variable name as function argument?

3.5k views Asked by At

I wish to make a function whose arguments are the name of a list L, and its arguments. The list L has just numbers in it, and I want to round them all to 1 decimal(by the way, the elements of the list L should be replaced by the rounded numbers, I don't want a new list M with them). Sadly, the list name varies in the script I'm planning, and so does the length of such lists. Here is my failed attempt:

def rounding(name,*args):  
    M=[round(i,1) for i in args] #here is the list I want L to become
    name=M   #here I try to replace the previous list with the new one

morada=[1,2.2342,4.32423,6.1231]  #an easy example
rounding(morada,*morada)
print morada

Output:

[1, 2.2342, 4.32423, 6.1231]  #No changes
3

There are 3 answers

0
rassar On BEST ANSWER

Have the rounding function return a value.

def rounding(list_):
    return [round(i, 1) for i in list_]

Then you can do this:

>>> morada=[1,2.2342,4.32423,6.1231]  #an easy example
>>> morada = rounding(morada)
>>> morada
[1, 2.2, 4.3, 6.1]

Or if you really really wanted it to assign within the function you could do this:

def rounding(list_):
    list_[:] = [round(i,1) for i in args]
0
Ignacio Vazquez-Abrams On

Close. Lists are mutable, so...

name[:] = M
3
schaazzz On

You can use eval()

For example, the following will start with a list containing [1, 2, 3, 4] and change the first element to 5:

list_0 = [1, 2, 3, 4]

def modify_list(arg):
  list_1 = eval(arg)
  list_1[0] = 5

modify_list('list_0')
print list_0