Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add value to a tuple?

Tags:

python

tuples

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?

like image 313
Shahzad Avatar asked Feb 06 '11 12:02

Shahzad


People also ask

How do you add a value to a tuple in Python?

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.

How do you add items to a tuple?

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.

Can you use += for tuples?

That's right: Adding a list to a tuple with + doesn't work. But if we use +=, it does.


2 Answers

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.

like image 126
AndiDog Avatar answered Oct 13 '22 15:10

AndiDog


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')] 
like image 24
atp Avatar answered Oct 13 '22 15:10

atp