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?
First, convert tuple to list by built-in function list(). You can always append item to list object. Then use another built-in function tuple() to convert this list object back to tuple. You can see new element appended to original tuple representation.
You can't add elements to a tuple because of their immutable property. There's no append() or extend() method for tuples, You can't remove elements from a tuple, also because of their immutability.
That's right: Adding a list to a tuple with + doesn't work. But if we use +=, it does.
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.
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')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With