how to add value to a tuple?
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?
Solution 1:
Tuples are immutable and not supposed to be changed - that is what the list type is for.
However, you can replace each tuple using 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.
Solution 2:
Based on the syntax, I'm guessing this is Python. The point of a tuple is that it is immutable, so you need to replace each element with a new tuple:
list = [l + (''.join(l),) for l in list]
# output:
[('1', '2', '3', '4', '1234'),
('2', '3', '4', '5', '2345'),
('3', '4', '5', '6', '3456'),
('4', '5', '6', '7', '4567')]
Solution 3:
As mentioned in other answers, tuples are immutable once created, and a list might serve your purposes better.
That said, another option for creating a new tuple with extra items is to use the splat operator:
new_tuple = (*old_tuple, 'new', 'items')
I like this syntax because it looks like a new tuple, so it clearly communicates what you're trying to do.
Using splat, a potential solution is:
list = [(*i, ''.join(i)) for i in list]