Home > Mobile >  converting a list with cubed defined function on python
converting a list with cubed defined function on python

Time:11-07

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.

CodePudding user response:

Replace the for loop with

CubedList = [cubed(x) for x in RangeList]

CodePudding user response:

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]

CodePudding user response:

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)
  • Related