Help understanding list operatoins inside functions in python 3

mortoxa mortoxa at gmx.com
Tue Jan 13 08:49:06 EST 2015


On 01/13/15 23:51, stephen.boulet at 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]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20150114/b441701c/attachment.html>


More information about the Python-list mailing list