multivariable assignment

John Posner jjposner at optimum.net
Thu Dec 31 14:19:32 EST 2009


On Thu, 31 Dec 2009 11:32:04 -0500, Andreas Waldenburger
<usenot at geekmail.invalid> wrote:

> On Thu, 31 Dec 2009 08:13:35 -0800 (PST) davidj411
> <davidj411 at gmail.com> wrote:
>
>> I am not sure why this behavior is this way.
>> at beginning of script, i want to create a bunch of empty lists and
>> use each one for its own purpose.
>> however, updating one list seems to update the others.
>>
>> >>> a = b = c = []
> No, you're only creating one list (and giving that one list three
> names). Creating three lists would be:
>
> a = []
> b = []
> c = []
>
> or, alternatively
>
> a, b, c = [], [], []
>
> Just remember: Python "variables" are just names that point to the
> actual data. "x = y" just means "make 'x' a synonym for 'y'".
>

Revising/expanding Andreas's last paragraph (trying to be correct, but not
trying to be complete):

Python deals with NAMEs and OBJECTs. A NAME is "bound" or "assigned" to an
OBJECT. Each OBJECT can have any number of NAMEs. A NAME cannot be
assigned to another NAME -- only to an OBJECT.

Objects are created by EXPRESSIONS, such as:

    42
    42 + 3*othernum
    "spam"
    "spam" + "eggs"
    empname[4:10] <-- slice of a string or other sequence
    cook("spam" + "eggs", 7)  <-- calling a function
    "spam".split()  <-- calling an object method
    Brunch("spam", veggie, dessert)  <-- instantiating a class

NAMEs are created by assignment statements. You can also reuse an existing
NAME in a subsequent assignment statement.

Some assignment statements are of the form:

     NAME = EXPRESSION

Ex:

     grand_total = 42
     paragraph = " ".join(sentence1, sentence2)
     grand_total = 42 + 3*othernum
     sunday_brunch = Brunch(Eggs(2), "broccoli", "cookie")

This form:

    1a. Creates a new NAME,
      or
    1b. Removes an existing NAME from the OBJECT to which it is currently
assigned.
     2. Assigns the NAME to the OBJECT created by the EXPRESSION.

Other assignment statements are of the form:

     NAME2 = NAME1

This form does not create a new OBJECT. Instead, it assigns NAME2 as an
additional name for the object to which NAME1 is currently assigned. Ex:

    y = x
    tenth_item = mylist[9]  <-- a list's items have auto-assigned integer
NAMEs
    clr = colors["sea foam"] <-- a dict has user-devised NAMEs called "keys"
    red_comp = rgb_color.red <-- a class instance has user-devised NAMEs
called "attributes"

My favorite metaphor for Python's NAMEs-and-OBJECTs scheme is the
Post-It(r). NAMEs are like Post-Its; you can stick any number of Post-Its
to any object.

HTH (and sorry if the above is overly pedantic),
John



More information about the Python-list mailing list