How to go through a list without using a "for i" loop

Question:

When the function gets called, the *args are a tuple so I have to append each argument to a list first. Then I sum them by mapping their values to float and using the sum() function.

There is nothing wrong whith this block of code, but I get a warning saying “Unused variable i”.

def function(*args):
    x = []
    y = 0
    for i in range(len(args)):
        x.append(args[y])
        y += 1
   x = list(map(float, x))
   return sum(x)

Is there a way to do this in some other way that doesn’t envolve using a “for i” loop and is more efficient?

Asked By: Gustavo Barros

||

Answers:

The pythonic way would be something like this:

def function(*args):
    return sum(float(x) for x in args)

Now, for explaining all this over your code. You can avoid using the variable y because it is doing exactly the same as i:

def function(*args):
    x = []
    for i in range(len(args)):
        x.append(args[i])
    x = list(map(float, x))
    return sum(x)

And then, you can avoid appending because you can use map over args:

def function(*args):
    x = list(map(float, args))
    return sum(x)

You can also just use map(float, args), no need to create an intermediate list for this purpouse:

def function(*args):
    x = map(float, args)
    return sum(x)

So it can be abstract as a generator inside sum, sum(float(x) for x in args), or with map sum(map(float, args)), same effect there.

Answered By: Netwave

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.

Answered By: r.ook
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.