1

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
Diego
  • 233
  • 1
  • 3
  • 9

3 Answers3

3

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]
rassar
  • 5,412
  • 3
  • 25
  • 41
1

Close. Lists are mutable, so...

name[:] = M
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

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  
schaazzz
  • 568
  • 5
  • 19
  • There's no need to do that sort of thing at all. You could do `arg[0] = 5` inside your `modify_list` function (passing `list_0` instead of `'list_0'`) and you would have the same effect. – Greg Hewgill Dec 20 '16 at 02:38
  • I'm not a big fan of this solution either, but if I understood the question correctly, the name of the list is unknown...and the OP _did_ _ask_ how to use the variable name as an argument. – schaazzz Dec 20 '16 at 02:40
  • Quite often what people *ask for* has little to do with what they *actually need*. They don't know how to ask for what they need. – Greg Hewgill Dec 20 '16 at 03:02