Reputation: 21927
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')
)
Upvotes: 74
Views: 127955
Reputation: 86
my_choices=(
('1','first choice'),
('2','second choice'),
('3','third choice')
)
new=('0','zero choice')
l=[item for item in my_choices]
l.insert(0,new)
my_choices=tuple(l)
print(my_choices)
Upvotes: 0
Reputation: 31
You could use the "unpacking operator" (*) to create a new tuple
tpl = ((2, 11), (3, 10),)
tpl = (*tpl, (5, 8))
print(tpl) #prints ((2, 11), (3, 10), (5, 8))
Upvotes: 3
Reputation: 16265
What you have is a tuple of tuples, not a list of tuples. Tuples are read only. Start with a list instead.
>>> my_choices=[
... ('1','first choice'),
... ('2','second choice'),
... ('3','third choice')
... ]
>>> my_choices.insert(0,(0,"another choice"))
>>> my_choices
[(0, 'another choice'), ('1', 'first choice'), ('2', 'second choice'), ('3', 'third choice')]
list.insert(ind,obj) inserts obj at the provided index within a list... allowing you to shove any arbitrary object in any position within the list.
Upvotes: 2
Reputation: 19353
Alternatively, use the tuple concatenation
i.e.
final_choices = (another_choice,) + my_choices
Upvotes: 8
Reputation: 123632
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,))
Upvotes: 35
Reputation: 76667
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)
Upvotes: 78