Asp Forum
Home
|
Login
|
Register
|
Search
Forums
>
comp.lang.python
Re: lists of variables
Chris Rebert
2/21/2010 3:35:00 AM
On Sat, Feb 20, 2010 at 7:25 PM, Michael Pardee
<python-list@open-sense.com> wrote:
> I'm relatively new to python and I was very surprised by the following behavior:
>
>>>> a=1
>>>> b=2
>>>> mylist=[a,b]
>>>> print mylist
> [1, 2]
>>>> a=3
>>>> print mylist
> [1, 2]
>
> Whoah! Are python lists only for literals? Nope:
>
>>>> c={}
>>>> d={}
>>>> mydlist=[c,d]
>>>> print mydlist
> [{}, {}]
>>>> c['x']=1
>>>> print mydlist
> [{'x': 1}, {}]
>
> So it looks like variables in a list are stored as object references.
> This seems to confirm that:
>
> mydlist[1]['y']=4
>>>> print mydlist
> [{}, {'y': 4}]
>
> So I figure my initial example doesn't work because if you assign a
> literal to something it is changing the object. But modifying a list
> or dict (as long as you don't re-construct it) does not change the
> object.
Correct. If you want more gory details, read
http://effbot.org/zone/call-by-...
> I can think of some ways to work around this, including using single
> element lists as "pointers":
>
>>>> aa=[1]
>>>> bb=[2]
>>>> myplist=[aa,bb]
>>>> print myplist
> [[1], [2]]
>>>> aa[0]=3
>>>> print myplist
> [[3], [2]]
>
>
> But what would be "the python way" to accomplish "list of variables"
> functionality?
What do you need that functionality for exactly? It's a rather low-level notion.
Cheers,
Chris
--
http://blog.re...
Servizio di avviso nuovi messaggi
Ricevi direttamente nella tua mail i nuovi messaggi per
Re: lists of variables
Inserendo la tua e-mail nella casella sotto, riceverai un avviso tramite posta elettronica ogni volta che il motore di ricerca troverà un nuovo messaggio per te
Il servizio è completamente GRATUITO!
x
Login to ForumsZone
Login with Google
Login with E-Mail & Password