On 01/13/15 23:51, stephen.bou...@gmail.com wrote:
I'm a bit confused why in the second case x is not [1,2,3]:

x = []

def y():
     x.append(1)

def z():
     x = [1,2,3]

y()
print(x)
z()
print(x)

Output:
[1]
[1]

In your y() function, as you are appending data, the list must already exist. So the global list x is used

In your z() function, you are creating a local list x which only exists as long as you are in the function. Anything you do to that list has no effect on the global list x. That is why the list does not change.

If you specifically wanted to change the global list x, you could do this:

def z():
    global x
    x = [1, 2, 3]

Output:
[1]
[1, 2, 3]

Or better

def z():
    x = [1, 2, 3]
    return x

y()
print(x)
x = z()
print(x)

Output:
[1]
[1, 2, 3]
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to