Tuples and immutability

Ian Kelly ian.g.kelly at gmail.com
Wed Mar 12 10:51:52 CET 2014


On Wed, Mar 12, 2014 at 3:39 AM, Antoon Pardon
<antoon.pardon at rece.vub.ac.be> wrote:
> The documentation is wrong at that point as the following code illustrates.

Either way it still has to do a getitem and a setitem, but if you have
a more nested structure then the extra getitems are not repeated.  For
example, using your logdict class:

>>> tab = logdict()
>>> tab[1] = logdict()
[1] <= <__main__.logdict object at 0x02A2E430>
>>> tab[1][2] = logdict()
[1] => <__main__.logdict object at 0x02A2E430>
[2] <= <__main__.logdict object at 0x02A2EB10>
>>> tab[1][2][3] = ['value']
[1] => <__main__.logdict object at 0x02A2E430>
[2] => <__main__.logdict object at 0x02A2EB10>
[3] <= ['value']
>>> tab[1][2][3] += [' with extra tail']
[1] => <__main__.logdict object at 0x02A2E430>
[2] => <__main__.logdict object at 0x02A2EB10>
[3] => ['value']
[3] <= ['value', ' with extra tail']

versus:

>>> tab[1][2][3] = ['value']
[1] => <__main__.logdict object at 0x02A2E430>
[2] => <__main__.logdict object at 0x02A2EB10>
[3] <= ['value']
>>> tab[1][2][3] = tab[1][2][3] + [' with extra tail']
[1] => <__main__.logdict object at 0x02A2E430>
[2] => <__main__.logdict object at 0x02A2EB10>
[3] => ['value']
[1] => <__main__.logdict object at 0x02A2E430>
[2] => <__main__.logdict object at 0x02A2EB10>
[3] <= ['value', ' with extra tail']

As you can see the += version does two fewer getitem calls in this case.



More information about the Python-list mailing list