help

Bengt Richter bokr at oz.net
Mon Sep 30 00:00:54 CEST 2002


On Tue, 24 Sep 2002 15:58:48 -0300, "Juliana Braga" <juliana at pdi.inpe.br> wrote:

>I need help.
>For example:
>x = ‘name1’
>How can I get the value of variable x (in this case the value of variable x
>is ‘name1’). After , I’d like to do this:
>value of variable x = ‘teste’.
>
The best advice I can give is to try things interactively.
And when you have a question about what happens, copy and paste it
right from your interactive session into your post.

Also, in Python it's best to think of attaching names to values
rather than setting values into named places.

I.e., what would an assignment be overwriting a value in C or many other languages
really just attaches the name on the left to a different value. Another name can still
be attached to the first value. E.g.,

 >>> x = 'name1' # attaches ('binds') name "x" to string value 'name1'
 >>> y = x       # binds name "y" to the same value as "x" is bound to.
 >>> print x,y
 name1 name1
 >>> x = 'teste' # binds name "x" to string value 'teste'
 >>> print x,y   # y should be unaffected by rebinding of x
 teste name1

The above looks ordinary, but when you attach a name to a "mutable" object
the differences start to become apparent, e.g.,

 >>> x = ['name1']
 >>> y = x          # bind y to same list object as x
 >>> print x,y
 ['name1'] ['name1']
 >>> x.append('teste') # modify the list object that x is bound to, but not the binding
 >>> print x,y
 ['name1', 'teste'] ['name1', 'teste']

The binding of y is still to the same object, so the modification we did via the x binding
to that object shows up via y also.

Some operations look the same for notation convenience but really do either rebinding or
mutation without rebinding, depending on the target. E.g., lists are mutable, but strings
are not, so:

 >>> x = 'name1'
 >>> y = x
 >>> x += 'teste'   # x will get rebound to something different than y, whose binding is unchanged
 >>> print x,y
 name1teste name1
 >>> x = ['name1']
 >>> y = x
 >>> x += ['teste'] # the object x is bound to will get modified, but x and y bindings don't change
 >>> print x,y
 ['name1', 'teste'] ['name1', 'teste']

so the modified list shows up via both x and y.


There is a good tutorial at

    http://www.python.org/doc/current/tut/tut.html

and many other documentation links at

    http://www.python.org/doc/

and of course you can start at the top

    http://www.python.org/

where you'll also find a link to a beginner's guide at

    http://www.python.org/doc/Newbies.html

Have fun. And [OT] thanks to you, we now have one more movie star
(last) name posting to c.l.p (along with Peters, Roberts, Holden, Davis, ...
;-)

Regards,
Bengt Richter



More information about the Python-list mailing list