[Python-ideas] Unpacking iterables for augmented assignment

Matthew Einhorn moiein2000 at gmail.com
Mon Aug 27 01:29:14 EDT 2018


On Sun, Aug 26, 2018, 9:24 PM James Lu <jamtlu at gmail.com> wrote:

> Hi Johnathan
>
> I echo your points. Indeed, the PEP referenced to refers to a "tuple
> expression" in the grammatical and not the programmatic sense.
>
> Finally, here's something that surprised me a little bit
>
> >>> x = [1, 2]; id(x)
> 140161160364616
> >>> x += [3, 4]; id(x)
> 140161160364616
>
> >>> x = (1, 2); id(x)
> 140161159928520
> >>> x += (3, 4); id(x)
> 140161225906440
>
> Notice that '+=' creates uses the same object when the object is
> a
> list, but creates a new object. This raises the question: Why and
> how
> does Python behave in this way?
>
> It's because lists are mutable are tuples are immutable.
> There's a dunder iadd method and a dunder add method.
> iadd magic methods, operating on the left hand side, return None and
> modify the object in-place. add magic methods return the result and
> don't modify the object it's called on.
> iadd is mutable add, whereas add is "return a copy with the result
> added"
>
> >>> tuple.__iadd__
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> AttributeError: type object 'tuple' has no attribute '__iadd__'
> type object 'tuple' has no attribute '__iadd__'
> >>> tuple.__add__
> <slot wrapper '__add__' of 'tuple' objects>
> >>> list.__iadd__
> <slot wrapper '__iadd__' of 'list' objects>
> >>> list.__add__
> <slot wrapper '__add__' of 'list' objects>
>
>
> tuple1 = tuple1.__add__(tuple2)
>
> list1.__iadd__(list2)
>
> > Does it IN PRACTICE bring sufficient benefits to users?
>
> I found myself needing this when I was writing a monte-carlo
> simulation in python that required incrementing a tallying counter
> from a subroutine.
>


Wouldn't a numpy array be very suited for this kind of task?

>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180827/a1c698af/attachment.html>


More information about the Python-ideas mailing list