How to append output values of a function to a new empty list?

Question:

My aim is to create a function, list_powers, and use a for loop to take a list and return a new list (power_list) where each element is exponentiated to a specified power.

I have moved the return statement appropriately in order to collect all topowers in power_list and return them but it still returns None. How do I change it so that it returns the list of powers?

def list_powers(collection = [], power = 2):
    power_list = []
    
    for elem in collection:
        topower = elem ** power
        power_list.append(topower)
    return power_list.append(topower)

test:

list_powers([2, 4, 1, 5, 12], power = 2)

output:

None
Asked By: JVR

||

Answers:

return leaves the function. You have to return after the loop, not unconditional in the loop. And of course you don’t want to return the last value for topower but the full list.

def list_powers(iterable, power = 2):
    power_list = []

    for elem in iterable:
        topower = elem ** power
        power_list.append(topower)

    return power_list

print(list_powers([2, 4, 1, 5, 12]))

The shorter version uses a list comprehension

def list_powers(iterable, power = 2):
    return [elem ** power for elem in iterable]
Answered By: Matthias

When you do return topower it stop the function therefore it will only return one value. If you want to return a list you should do return power_list and outside of the local scope.

Answered By: Trimonu
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.