-2

I have created a range list - [2, 4, 6, 8, 10]

    RangeList = list(range(2,11,2))
    RangeList

   [2, 4, 6, 8, 10]

I need to convert this list into [8, 64, 216, 512, 1000] The criteria i am working with:

-use a for loop and the 'cubed' function defined to convert the above list to

-[8, 64, 216, 512, 1000]

def cubed(x):
y = x**3
print('  %s'%(y))
return(y)

for x in RangeList:
cubed(x)

 8
64
216
512
1000

What am i missing in my code to get this to present as a straight list with commas.

esco
  • 71
  • 4

3 Answers3

0

Replace the for loop with

RangeList = list(range(2,11,2))
CubedList = [x**3 for x in RangeList]
CubedList
cmay
  • 153
  • 6
  • that seems to return the same result – esco Nov 06 '21 at 22:22
  • Here's a modified version, as someone said, you are printing off within the cubed function, so it is printing off each iteration as opposed to the final list. – cmay Nov 07 '21 at 00:11
0

You could make a list and append to the list one by one using for loop like this:

l=[]
for x in RangeList:
    l.append(cubed(x))
print(l)

or, you can use list comprehension.

l = [cubed(x) for x in RangeList]
jeff pentagon
  • 796
  • 3
  • 12
0

You need to use an empty list before your loop. And use .append(). Or you can use the list comprehension like in the comment.

RangeList = list(range(2,11,2))
def cubed(x):
    y = x**3
    return(y)

newList = []
for x in RangeList:
   newList.append(cubed(x))
print(newList)
uKioops
  • 269
  • 3
  • 8