Why it says change n[i] to x[i]?


#1

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

    return n

print double_list(n)


#2

Consider,

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

What prints outs?

[6, 10, 14]

Think on this for the moment and we'll pick up from here, later.


#3

Yes i am completely agree with the code ..


#4

Notice that n, which is global, is modified by the loop? That is the import of this first demonstration.

What if we pass in another list (leaving n intact)? Can you guess what will happen then?

n = [3, 5, 7]
o = [11, 13, 17]
def double_list(n):
    for i in range(len(n)):
        n[i] *= 2

double_list(n)
print n
double_list(o)
print o
print n

Console output

[6, 10, 14]
[22, 26, 34]
[6, 10, 14]

When we passed n it was global an did not rely upon the return value. It was visible in global scope and the function changed it. Notice we did not print the return value? Only n.

The object we pass in, if it exists in global scope will stay in global scope, regardless that we gave it to a function. The function does not copy it. Merely refers to it.


#5

Python is actually pretty smart this way. JavaScript would never let us get away with the above code, but that is for another day.

The question is Why it say change n[i] to x[i]?, and the answer is quite simply so that we can see how changing the name of the variable inside the function does not create a new object owing that a list and a dictionary are both reference objects. The x[i] inside the function is actually the n[i], just with a different name. They are both the one object.

n => [ ... ] <= x

From a practical point of view, while Python may be able to handle things regardless, we should use local names in our functions that do not exist in the global namespace but remain generic to the function and their purpose. This helps with readability and debugging.


#6

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