python - I would like to know, what is the difference between these two code samples. One works and the other does not -


# sample 1 , work. long n = [3, 5, 7] def double_list(x):     in range(0, len(x)):         x[i] = x[i] * 2     return(x) print(double_list(n))  # sample 2 , not work. n = [3, 5, 7] def double_list(x):     in x:          = * 2     return(x) print(double_list(n)) 

the codes above meant take items of list entered , multiply each item of list two, return list.

i want know, why 1 first 1 work, , why second 1 not work. second 1 shorter. first 1 takes index , uses index call item , multiplys. second directly multiplys item. second more concise, why not work?

in first example accessing list using the

x[i] = x[i] * 2 

so use local variable "i" access list element index , change content of it.

however in second example not access list x, since working local variable "i". not change list , list remains unchanged. can tell this, because if accessing list, have written sth like

x[i] = 

or

x = 

if have further questions feel free ask.


Comments