Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append one value to every tuple within a list?

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.

like image 237
Chris Avatar asked Sep 02 '25 02:09

Chris


2 Answers

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.

like image 86
Amber Avatar answered Sep 05 '25 07:09

Amber


You can apply a map with lambda-function for this:

new_list = map(lambda x: [111] + list(x), tuple_list)
like image 26
sashkello Avatar answered Sep 05 '25 06:09

sashkello