Confusing bug with brackets on my function
<pre><code>def cube_of(valz):Â Â Â Â 
Â Â Â Â '''Returns the cube of values'''Â Â Â Â 
Â Â Â Â if len(valz) == 0:Â Â Â Â 
Â Â Â Â Â Â Â Â return 0Â Â Â Â 
Â Â Â Â else:Â Â Â Â 
Â Â Â Â Â Â Â Â new_val = [valz[0] ** 3]Â Â Â Â 
Â Â Â Â Â Â Â Â returnÂ Â [new_val] + [cube_of(valz[1:])]Â 
</code></pre>

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

<p>For example, let's say the input is <code>[-1,2,-3,4,-5]</code> - it should return <code>[-1,8,-27,64,-125]</code> but it returns <code>[-1, [8, [-27, [64, [-125, 0]]]]]</code>.
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 <code>int</code> to a <code>list</code>). I tried to debug this and even had my friend take a look but we're both pretty stumped.</p>

<p><code>cube_of(valz)</code> already returns an initial segment of the list in the <code>else</code> part of the branch, i.e. <code>[new_val]</code>. Therefore, in order for its overall return value to be of type list, it should return lists in all its branches.</p>

<p>You should change the function like this:</p>

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

<p>Note that now, since both branches of the if-else return an initial segment of the final list, <code>cube_of</code> itself now returns a list by induction, thereby making the entire recursive call return a value of list type.</p>

<p>However, if you're looking for an elegant and more idiomatic/Pythonic solution, look no further than anonymous'.</p>

python recursion