[Tutor] More or less final Chutes & Ladders
spir
denis.spir at gmail.com
Sat Jan 4 14:25:56 CET 2014
On 01/04/2014 02:03 PM, Steven D'Aprano wrote:
>> >I'm also a bit confused here: obviously tuples are immutable, but one can
>> >use lists in them... I think that makes those lists' contents immutable?
> Nope. It makes the tuple immutable in the sense that it's *direct*
> contents cannot be changed, but mutable in the sense that the contents
> of the tuple can be mutated.
>
> py> t = (1, 2, [])
> py> t[2] = ["hello"]
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: 'tuple' object does not support item assignment
> py> t[2].append("hello")
> py> t
> (1, 2, ['hello'])
>
>
>> >And could one define a namedtuple that included lists that were different
>> >lengths for different instantiations (like my game results, for example)?
> Naturally. The nametuple doesn't care what you put inside it.
I used to explain this by making people note that there 2 ways of *changing* a
given item (or field, or any var for the matter), if its value is complex &
mutable: *replacing* vs *modifying*:
l = [1,2,3]
l = [1,0,3] # replace (by brand new value/object)
l[1] = 0 # modify (the value/object itself)
When a symbol's value is simple or mutable, one can only replace it. (You can
change _only_ the second digit of "123", or its n-th bit in binary
representation, or the fractional part of "-123.45", less so its sign ;-).
Denis
More information about the Tutor
mailing list