Modifying Each Element in a List in a Function


#1

The directions are:
Create a function called double_list that takes a single argument x (which will be a list) and multiplies each element by 2 and returns that list. Use the existing code as a scaffold.

I used the correct code, but why does the return code have to be 'return x'?

My code (I did use proper indentation, but this post does not reflect that):

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

Don't forget to return your new list!

print double_list(n)


#2

Can code be correct if we do not understand it? This is the sort of question that comes up when copied code is used. It works, but surprises the user for lack of explanation and an understanding of the problem.

Why return x, because,

The input list is modified, then returned.


#3

Thanks MTF. It makes sense that returning X rather than x[1].


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.