how to add value to a tuple?

Shahzad picture Shahzad · Feb 6, 2011 · Viewed 197.3k times · Source

I'm working on a script where I have a list of tuples like ('1','2','3','4'). e.g.:

list = [('1','2','3','4'),
        ('2','3','4','5'),
        ('3','4','5','6'),
        ('4','5','6','7')]

Now I need to add '1234', '2345','3456' and '4567' respectively at the end of each tuple. e.g:

list = [('1','2','3','4','1234'),
        ('2','3','4','5','2345'),
        ('3','4','5','6','3456'),
        ('4','5','6','7','4567')]

Is it possible in any way?

Answer

AndiDog picture AndiDog · Feb 6, 2011

Tuples are immutable and not supposed to be changed - that is what the list type is for. You could replace each tuple by originalTuple + (newElement,), thus creating a new tuple. For example:

t = (1,2,3)
t = t + (1,)
print t
(1,2,3,1)

But I'd rather suggest to go with lists from the beginning, because they are faster for inserting items.

And another hint: Do not overwrite the built-in name list in your program, rather call the variable l or some other name. If you overwrite the built-in name, you can't use it anymore in the current scope.