13 - Strange indentation errors?


#1

Hello, If i type

n = [3, 5, 7]

def double_list(x):
for i in range(0, len(x)):
x[i] = x[i] * 2
return x

print double_list(n)

I receive [6,5,7] as a response.

However if i back tab return x once making the code

n = [3, 5, 7]

def double_list(x):
for i in range(0, len(x)):
x[i] = x[i] * 2
return x

print double_list(n)

I receive the correct response of [6,10,14]. Why does this one indentation change the outcome entirely?


#2

to explain this you will have to know this

Whenever you call return in a function it the function will terminate and the value returned will be 
handed over to its caller(and it can be captured and stored in a variable)

Down here take a look at the first code you wrote with comments why it did not give you the right results

def double_list(x):
    #the method contract
    '''This method takes an input list of ints
        and doubles each value
        :param x the list to parse
    '''
    #here you start looping through all the valid indices 
    #in the given list awesome
    for i in range(0, len(x)):
        #at each index you are getting the element and doubling it
        #in memeory
        x[i] = x[i] * 2
        print ("The doubled list si currently %s"%x)
        #after that the interpreter gets here but wait
        #whenever we call return in a function  its like we are done 
        # with the function hence the function will terminate
        #(so will the for loop) and the
        # the final value of the list is returned
        return x
        
print double_list([2,3,4,5]) #[4, 3, 4, 5]

click here to test

Now lets take a look at why the second one worked

def double_list(x):
    #the method contract
    '''This method takes an input list of ints
        and doubles each value
        :param x the list to parse
    '''
    #here you start looping through all the valid indices 
    #in the given list awesome
    for i in range(0, len(x)):
        #at each index you are getting the element and doubling it
        #in memeory
        x[i] = x[i] * 2
        print ("The doubled list is currently %s\n"%x)
    
    #notice how the return statement is outside the for loop
    #it means by the time the intepreter executes this statement
    #the for loop has completely ran and doubled every value in memory
    #Then finally you throw the new modified list to its caller and
    #then the function terminates
    return x
        
print double_list([2,3,4,5]) #[4, 6, 8, 10]

Click here to test


13/18 Modifying each element in a list in a function
#3

Thanks for this answer!! Makes total sense now.


#4

It turns out I had a problem with an indentation. Thank you so much!:smile: