Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add another tuple to a tuple of tuples

Tags:

python

tuples

I have the following tuple of tuples:

my_choices=(          ('1','first choice'),          ('2','second choice'),          ('3','third choice') ) 

and I want to add another tuple to the start of it

another_choice = ('0', 'zero choice') 

How can I do this?

the result would be:

final_choices=(              ('0', 'zero choice')              ('1','first choice'),              ('2','second choice'),              ('3','third choice')     ) 
like image 838
John Avatar asked Aug 19 '10 14:08

John


People also ask

How do you add a tuple 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.

Can you add 2 tuples together?

You can, however, concatenate 2 or more tuples to form a new tuple. This is because tuples cannot be modified.

Can you append tuples?

Appending a tuple in Python is not possible because it is an immutable object. But there is another way in which you can add an element to a tuple. To append an element to a tuple in Python, follow the below steps. Convert tuple to list using the list() method.


2 Answers

Build another tuple-of-tuples out of another_choice, then concatenate:

final_choices = (another_choice,) + my_choices 

Alternately, consider making my_choices a list-of-tuples instead of a tuple-of-tuples by using square brackets instead of parenthesis:

my_choices=[      ('1','first choice'),      ('2','second choice'),      ('3','third choice') ] 

Then you could simply do:

my_choices.insert(0, another_choice) 
like image 198
Daniel Stutzbach Avatar answered Sep 22 '22 03:09

Daniel Stutzbach


Don't convert to a list and back, it's needless overhead. + concatenates tuples.

>>> foo = ((1,),(2,),(3,)) >>> foo = ((0,),) + foo >>> foo ((0,), (1,), (2,), (3,)) 
like image 35
Katriel Avatar answered Sep 26 '22 03:09

Katriel