I just tried the following in Python 2.6:
>>> foo = (set(),)
>>> foo[0] |= set(range(5))
TypeError: 'tuple' object does not support item assignment
>>> foo
(set([0, 1, 2, 3, 4]),)
>>> foo[0].update(set(range(10)))
>>> foo
(set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),)
I have a few questions:
- Why
foo[0] |= set(range(5))updates the set and throws an exception? - Why
foo[0].update(set(range(10)))does it work without problems? Should it have the same result as the first statement?
Change . Many people have indicated that tuples are immutable. I know about it. They also noted that they |=would create a new object setand assign it to a tuple. It is not right. See this:
>>> foo = set()
>>> bar = foo
>>> foo is bar
True
>>> foo |= set(range(5))
>>> foo
set([0, 1, 2, 3, 4])
>>> bar
set([0, 1, 2, 3, 4])
>>> foo is bar
True
, , . . , TypeError, . , . TypeError, , , ?