How to append 1 value to every tuple within a list?
tuple_list = [('a','b'),('c','d'),('e','f')]
value = 111
Desired_List = [(111,'a','b'),(111,'c','d'),(111,'e','f')]
I've tried the following:
for x in tuple_list:
x.append(111)
for x in tuple_list:
x + '111'
I prefer sublists over tuples, so is there anyway to change the tuples to sublists as well?
Notes: It actually doesn't matter whether the 111 is in the first index or the last index of the tuple.
You can use a list comprehension to do both of the things you're looking to do.
To prefix:
desired_list = [[value]+list(tup) for tup in tuple_list]
To suffix:
desired_list = [list(tup)+[value] for tup in tuple_list]
The list()
call transforms each tuple into a list, and adding another list which contains only value
adds that value to each list once it has been created.
You can apply a map
with lambda-function for this:
new_list = map(lambda x: [111] + list(x), tuple_list)
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