15

How can I raise the numbers in list to a certain power?

Amelia155
  • 161
  • 1
  • 1
  • 5

9 Answers9

14

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

Jorick Spitzen
  • 1,559
  • 1
  • 13
  • 25
5

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)
Robert Calhoun
  • 4,823
  • 1
  • 38
  • 34
4

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.

Community
  • 1
  • 1
tommy.carstensen
  • 8,962
  • 15
  • 65
  • 108
2
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

konart
  • 1,714
  • 1
  • 12
  • 19
0

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)
maggick
  • 1,362
  • 13
  • 23
0

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)
GiovanniPi
  • 260
  • 1
  • 8
0

Use a list comprehension for some increased speed:

print('Original list:', numbers)
print('Cubic list:', [n**3 for n in numbers])
dermen
  • 5,252
  • 4
  • 23
  • 34
0
print(list(map(pow,numbers,repeat(2)))
double-beep
  • 5,031
  • 17
  • 33
  • 41
0

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]