1

I was thinking if I have a tuple of int and list:

(5,[2,3])

The first element id represents the sum of the list.

Can I append a value to the list and update the sum at the same time? The results should look something like this:

(10,[2,3,5])

Thanks for any help.

Kei
  • 611
  • 2
  • 11
  • 24
  • You cannot mutate a tuple, you can mutate objects contained in a tuple, but since `int` objects are immutable, you'll have to build a new tuple. Thisshould be simple though:`lst = t[1]; lst.append(val); new_t = (sum(lst), lst)` – juanpa.arrivillaga Feb 07 '18 at 22:34
  • @Kei, going backwards, do you really need to keep your variable as a `tuple`? – jpp Feb 07 '18 at 22:36

4 Answers4

3

No, you can't because tuples are immutable and therefore the sum can not be modified. You will have to create a new tuple.

>>> t = (5,[2,3])
>>> val = 5
>>> t_new = t[0] + val, t[1] + [val]
>>> t_new
(10, [2, 3, 5])

However, you might want to consider using a mutable data structure in the first place.

wim
  • 338,267
  • 99
  • 616
  • 750
3

You can do this like this:

def addTup(tup, x):
    return (tup[0]+x, tup[1]+[x])

a = (5,[2,3])
addTup(a, 22)

You have to create a new tuple which mainly consists out of the values of the old tuple. This code will add the new item to your list and will update the sum value simultaneously. You cannot simply modify the tuple it self, as tuples are immutable in python, as you can see here.

zimmerrol
  • 4,872
  • 3
  • 22
  • 41
1

Since tuples are immutable, you will have to create an entirely new tuple:

_, b = (5,[2,3])
final_results = (sum(b+[5]), b+[5])

Output:

(10, [2, 3, 5])
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
1

This is just a fancy version of @FlashTek's answer. The real question is whether there is a purpose to holding these values in a tuple if they are not immutable.

from collections import namedtuple

def add_value(n, x):
    return n._replace(arrsum=n.arrsum+x, arr=n.arr+[x])

SumArray = namedtuple('SumArray', ['arrsum', 'arr'])

s = SumArray(5, [2, 3])

t = add_value(s, 10)
# SumArray(arrsum=15, arr=[2, 3, 10])
jpp
  • 159,742
  • 34
  • 281
  • 339