13/18 not able to understand


#1

why is this code correct and not the next one ?

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

does the n or x make a difference?
thanks in advance!


#2

Yes, a big difference. x is defined and n is not (unless elsewhere). If n is the list that was passed in there is no need to return it. Inspect n after the function and you should see that it has changed from what it was before being passed to the function.

This is confusing until we begin to understand how lists and dictionaries behave in a function. They are not passed to the function like a simple value, such as a number, string or boolean would be. Only their location (reference pointer) is passed to the function. Any manipulation of the object inside the function is taking place on the globally referenced one.


#3

thanks very much mtf!!!:grinning::grinning::grinning:


#4

To illustrate:

>>> n = [2,4,8,16,32]
>>> def double_list(x):
  for i in range(0, len(x)):
    x[i] = x[i] * 2
  return x

>>> print (double_list(n))
[4, 8, 16, 32, 64]
>>> n
[4, 8, 16, 32, 64]
>>> 

The print statement is printing the return value, the list from the function. Now when we inspect n we see it too has been altered. Let’s see what happens when the return statement is removed.

>>> n = [2,4,8,16,32]
>>> def double_list(x):
  for i in range(0, len(x)):
    x[i] = x[i] * 2
    
>>> double_list(n)
>>> n
[4, 8, 16, 32, 64]
>>> 

It’s early into the course so this concept may not yet have surfaced. Stick to the introductory path and set the concern aside, for the moment. The subject of reference objects will come up, very soon I suspect.

Bookmark this topic so you can come back when the following example has more meaning…

>>> n = [2,4,8,16,32]
>>> def double_list(x):
  y = x[:]
  for i in range(0, len(y)):
    y[i] = y[i] * 2
  return y

>>> print (double_list(n))
[4, 8, 16, 32, 64]
>>> n
[2, 4, 8, 16, 32]
>>> 

#5

thanks for making me understand!!!
:rofl::smiley::smile:


#6

i have bookmarked it according to your advice


#7

When you get to the end of the module on Advanced topics will be the time to return to the following (return to the earlier example when you get into list slicing)…

>>> def double_list(x):
	return [2 * x[y] for y in range(len(x))]

>>> n = [2,4,8,16,32]
>>> print (double_list(n))
[4, 8, 16, 32, 64]
>>> n
[2, 4, 8, 16, 32]
>>> 

#8

no offence but i dont understand why you put that code


#9

Something to come back to when you get that far. Ignore it, for now.


#10

ok thanks anyway:smile::smile:


#11

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