0

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
JVR
  • 23
  • 4
  • 1
    Your function returns whatever and whenever you ask it to return. In this case, you asked it to return immediately after it calculated the first `elem ** power`. It does exactly what you asked it to do. If you want to collect all `topower`s in `power_list` and return that list _after_ you've finished the loop, move your return statement appropriately – Pranav Hosangadi Nov 22 '22 at 22:55
  • I knew there had to be a duplicate, but I couldn't find it. – Matthias Nov 22 '22 at 23:03

2 Answers2

2

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]
Matthias
  • 12,873
  • 6
  • 42
  • 48
1

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.

Trimonu
  • 44
  • 3