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') )
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, however, concatenate 2 or more tuples to form a new tuple. This is because tuples cannot be modified.
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.
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)
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,))
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