You didn't have to introduce y
when i
is already doing the job for you:
def function(*args):
x = []
# y = 0 <-- This is not necessary
for i in range(len(args)):
x.append(args[i]) # <-- change to [i]
# y += 1
# i increments by 1 each loop.
x = list(map(float, x))
return sum(x)
Of course, you can further reduce this function by looping directly through args
instead of the range
of it:
def function(*args):
x = []
for arg in args:
# directly loops through the elements within your args
x.append(arg)
x = list(map(float, x))
return sum(x)
You might even want to combine the float
operation while you append to avoid the map
afterwards:
def function(*args):
x = []
for arg in args:
x.append(float(arg))
return sum(x)
What's more, you can make use of list comprehension to make this even shorter:
def function(*args):
x = [float(arg) for arg in args]
# does the same thing as above
return sum(x)
Or, just combine everything into one line:
def function(*args):
return sum(float(arg) for arg in args)
Of course, depending on the complexity of your requirement, you might want to validate each elements before you cast them as floats
via try... except
blocks.