Tuples and immutability

albert visser albert.visser at gmail.com
Sun Mar 2 09:37:44 EST 2014


On Sun, 02 Mar 2014 15:17:11 +0100, Eric Jacoboni  
<eric.jacoboni at gmail.com> wrote:

> Le 02/03/2014 15:05, Mark Lawrence a écrit :
>
>> The behaviour is consistent except when you try to modify a tuple.
>>
>
> Not in my opinion...
>
> li = [10, 30]
> li = li + "spam"   --> TypeError: can only concatenate list (not "str")
> li += "spam"       --> Ok
>

possibly because you expect += to take "spam" as a string, but have you  
looked at the result?

In [1]: mylist = ['1', '2']

In [2]: mylist += 'spam'

In [3]: mylist
Out[3]: ['1', '2', 's', 'p', 'a', 'm']

consequently, try adding something that can not be interpreted as a  
sequence:

In [4]: mylist += 3
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-782b544a29d1> in <module>()
----> 1 mylist += 3

TypeError: 'int' object is not iterable


-- 
Vriendelijke groeten / Kind regards,

Albert Visser

Using Opera's mail client: http://www.opera.com/mail/



More information about the Python-list mailing list