Jawndoyghboi1569 Jawndoyghboi1569 - 5 months ago 26
Python Question

Confusing bug with brackets on my function

def cube_of(valz):    
    '''Returns the cube of values'''    
    if len(valz) == 0:    
        return 0    
        new_val = [valz[0] ** 3]    
        return  [new_val] + [cube_of(valz[1:])] 

So I am making this function for a demonstration which takes a list of values called
and takes the cube of each value and then returns a list of these cubes.

For example, let's say the input is
- it should return
but it returns
[-1, [8, [-27, [64, [-125, 0]]]]]
What is causing the extra brackets? If I remove the brackets in the code then it either gives the sum of these cubes (which is not correct) or it gives an error (something about adding an
to a
). I tried to debug this and even had my friend take a look but we're both pretty stumped.


If valz is empty you should return empty list instead of 0 - return []

new_valz is a list so you don't need brackets. cube_of returns list so you don't need brackets too.

def cube_of(valz):    
    '''Returns the cube of values'''    
    if len(valz) == 0:    
        return []    
        new_val = [valz[0] ** 3]    
        return  new_val + cube_of(valz[1:])

# [-1,8,-27,64,-125]

# []