The Student Room Group

Python array problem

Question: create a function that returns an array of the cube of each number in the range of two given numbers. E.g (1, 4) ==> [1, 8, 27, 64]

So far I have:
def cube_array(x, y):
for i in range(x, y + 1):
print(i**3)

I'm unsure how to get the output of the function into array form
Try this:


def cube_array(x, y):
array = []
for i in range(x, y + 1):
array.append(i**3)
return array

Reply 2
Original post by Strange5050
Try this:


def cube_array(x, y):
array = []
for i in range(x, y + 1):
array.append(i**3)
return array



Perfect, thank you.
You could take it a step further and put it as a neat one-liner using a list comprehension:

def cube_list(x, y):
return [i ** 3 for i in range(x, y + 1)]

print(cube_list(1, 4))
# [1, 8, 27, 64]


You could also use lambda here too:

>>> (lambda x, y: [i ** 3 for i in range(x, y + 1)])(1, 4)
# [1, 8, 27, 64]
(edited 2 years ago)

Quick Reply

Latest