RE: Augmented Assignment question

Discussion in 'Python' started by Delaney, Timothy C (Timothy), Jul 17, 2003.

  1. > From: Doug Tolton [mailto:]
    >
    > I mis-spoke, lists are not included. You cannot do augmented
    > assignments on tuples or multiple targets.


    This is still incorrect. You correct thing to say is that you cannot do an augmented assignment on something which does not have a name, or which explicitly forbids it.

    > >>> a,b = 0,0
    > >>> a,b += 1,1

    > SyntaxError: augmented assign to tuple not possible


    >>> l = []
    >>> l

    []
    >>> id(l)

    8289204
    >>> l += [1,]
    >>> l

    [1]
    >>> id(l)

    8289204
    >>> l += ['foo',]
    >>> l

    [1, 'foo']
    >>> id(l)

    8289204
    >>> t = ()
    >>> t

    ()
    >>> id(t)

    7966916
    >>> t += (1,)
    >>> t

    (1,)
    >>> id(t)

    8261268
    >>> t += ('foo',)
    >>> t

    (1, 'foo')
    >>> id(t)

    8133748

    Note how the ID of `l` (list) does not change, but the id of `t` (tuple) does. This is because a tuple is immutable, and so:

    t += (1,)

    is equivalent to:

    t = t + (1,)

    whereas a list is mutable, and:

    l += [1,]

    is equivalent to:

    l.extend([1,])

    Every class can decide how to implement augmented assignment, using the __iadd__, etc magic methods.

    Tim Delaney
    Delaney, Timothy C (Timothy), Jul 17, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Doug Tolton

    Augmented Assignment question

    Doug Tolton, Jul 16, 2003, in forum: Python
    Replies:
    6
    Views:
    477
    John Machin
    Jul 19, 2003
  2. Pierre Barbier de Reuille

    User-defined augmented assignment

    Pierre Barbier de Reuille, Sep 29, 2005, in forum: Python
    Replies:
    4
    Views:
    302
    Tom Anderson
    Oct 2, 2005
  3. Suresh Jeevanandam

    Augmented assignment

    Suresh Jeevanandam, Feb 21, 2006, in forum: Python
    Replies:
    8
    Views:
    330
    Terry Hancock
    Feb 21, 2006
  4. Josiah Carlson
    Replies:
    4
    Views:
    348
    Boris Borcic
    Jun 19, 2006
  5. Tim N. van der Leeuw

    Nested scopes, and augmented assignment

    Tim N. van der Leeuw, Jul 4, 2006, in forum: Python
    Replies:
    39
    Views:
    785
    Piet van Oostrum
    Jul 10, 2006
Loading...

Share This Page