0

I have

tuples = (('a',), ('b',), ('c',), ('d',))

I tried to update it with the following code.

for tup in tuples:
    tup += (1,)
print tuples

I expected the result will be (('a',1), ('b',1), ('c',1), ('d',1)). But it printed the same as the original value. Why? When I inserted print tup in the loop, I saw that tup was updated.

timgeb
  • 76,762
  • 20
  • 123
  • 145
iparjono
  • 361
  • 1
  • 2
  • 9

3 Answers3

3

Because tuples are immutable. tup += (1,) will return a new tuple with which you do nothing in your loop.

That being said, here you go:

>>> tuples = (('a',), ('b',))
>>> tuple(tup + (1,) for tup in tuples)
(('a', 1), ('b', 1))
timgeb
  • 76,762
  • 20
  • 123
  • 145
  • 1
    Given that the OP needs to have something that's mutable, I think you should've suggested the use of mutable objects, such as lists... – code_dredd Dec 21 '15 at 09:24
2

tuples are immutable, you can't update it but you can build a new one.

>>> l = (('a',), ('b',), ('c',), ('d',))
>>> tuple((i[0],1) for i in l)
(('a', 1), ('b', 1), ('c', 1), ('d', 1))
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
2

As others have already noted, tuples are immutable. Therefore, they cannot be modified. If you need mutability to allow modification, then you should use a list instead.

>>> # tuples; immutable
>>> tt = ((1, 2, 3), (1, 2, 3), (1, 2, 3))
>>> tt
((1, 2, 3), (1, 2, 3), (1, 2, 3))
>>> for e in tt: e += (4, )
...
>>> tt
((1, 2, 3), (1, 2, 3), (1, 2, 3))

>>> # lists; mutable
>>> ll = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> ll
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> for e in ll: e += [4]
...
>>> ll
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]

As shown above, if you use lists, you should be able to get what you want.

code_dredd
  • 5,915
  • 1
  • 25
  • 53