Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #83693

Re: Help understanding list operatoins inside functions in python 3

Date 2015-01-14 00:49 +1100
From mortoxa <mortoxa@gmx.com>
Subject Re: Help understanding list operatoins inside functions in python 3
References <eb7dcc11-410d-44a9-b619-e5ae70876aa1@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.17675.1421159068.18130.python-list@python.org> (permalink)

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view raw

On 01/13/15 23:51, stephen.boulet@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]

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Help understanding list operatoins inside functions in python 3 stephen.boulet@gmail.com - 2015-01-13 04:51 -0800
  Re: Help understanding list operatoins inside functions in python 3 Joel Goldstick <joel.goldstick@gmail.com> - 2015-01-13 08:39 -0500
  Re: Help understanding list operatoins inside functions in python 3 Laurent Pointal <laurent.pointal@laposte.net> - 2015-01-13 14:43 +0100
  Re: Help understanding list operatoins inside functions in python 3 mortoxa <mortoxa@gmx.com> - 2015-01-14 00:49 +1100
  Re: Help understanding list operatoins inside functions in python 3 Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2015-01-13 09:25 -0500

csiph-web