How can I raise the numbers in list to a certain power?
-
1What didn't work? What was the actual output you got? – SuperBiasedMan May 19 '15 at 10:50
-
my_list[i]=my_list[i]**3 modify your original list. – Eric Levieil May 19 '15 at 10:51
-
I think the question lacks details. Those which were deleted in the edit might be a start.... – Yunnosch Jun 09 '21 at 07:14
9 Answers
Use list comprehension:
def power(my_list):
return [ x**3 for x in my_list ]
https://docs.python.org/3.4/tutorial/datastructures.html#list-comprehensions

- 1,559
- 1
- 13
- 25
Another map
pattern, using lambda
instead of function.partial()
:
numbers=[1,2,3,4]
squares=list(map(lambda x:pow(x,2),numbers))
print(squares)

- 4,823
- 1
- 38
- 34
Nobody has mentioned map
and functools.partial
and the accepted answer does not mention pow
, but for the sake of completeness I am posting this solution:
import functools
bases = numbers = [1,2,3]
power = exponent = 3
cubed = list(map(functools.partial(pow, exponent), numbers))
I would use a list comprehension myself as suggested, but I think functools.partial
is a very cool function that deserves to be shared. I stole my answer from @sven-marnach here by the way.

- 1
- 1

- 8,962
- 15
- 65
- 108
def turn_to_power(list, power=1):
return [number**power for number in list]
Example:
list = [1,2,3]
turn_to_power(list)
=> [1, 2, 3]
turn_to_power(list,2)
=> [1, 4, 9]
UPD: you should also consider reading about pow(x,y)
function of math
lib: https://docs.python.org/3.4/library/math.html

- 1,714
- 1
- 12
- 19
You can simply do:
numbers=[1,2,3,4,5,6,7,8,9]
numbers3 = []
for n in numbers:
numbers3.append(n**3)
print('Original list:', numbers)
print('Cubic list:', numbers3)

- 1,362
- 13
- 23
Actually your script do what you want, and that is the result (keep in mind that you are applying the power function to [1,2,3,4,5,6,7,8,9])
('Cubic list:', [1, 8, 27, 64, 125, 216, 343, 512, 729])
Your problem is that you also modified the original list, due to the nature on the list type in python. If you want to keep also your original list you should pass a copy of it to your function. You can do it like this
def main():
numbers=[1,2,3,4,5,6,7,8,9]
numbers3=power(numbers[:])
print('Original list:', numbers)
print('Cubic list:', numbers3)

- 260
- 1
- 8
Use a list comprehension for some increased speed:
print('Original list:', numbers)
print('Cubic list:', [n**3 for n in numbers])

- 5,252
- 4
- 23
- 34
print(list(map(pow,numbers,repeat(2)))

- 5,031
- 17
- 33
- 41

- 11
- 2
-
3Please add an explanation as to how this works, and use the code formatting tabs. – Hoppo Jun 03 '20 at 13:45
I have created a random list by taking an input from the user, lets call that 'n' and squared the numbers in the list.
n = int(input("Enter a number"))
list1 = [*range(0,n,1)]
list2 = [number ** 2 for number in list1]