Kei
Kei

Reputation: 621

Add value to a tuple of list and int in Python3

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.

Upvotes: 1

Views: 1568

Answers (4)

jpp
jpp

Reputation: 164843

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])

Upvotes: 1

Ajax1234
Ajax1234

Reputation: 71471

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])

Upvotes: 1

zimmerrol
zimmerrol

Reputation: 4951

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.

Upvotes: 3

wim
wim

Reputation: 363566

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.

Upvotes: 3

Related Questions