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.