3

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.

Chris
  • 5,444
  • 16
  • 63
  • 119

3 Answers3

9

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.

Amber
  • 507,862
  • 82
  • 626
  • 550
  • 2
    I think this solution is slightly off-mark since the OP wanted a list of tuples, not a list of lists. Simple fix using the provided solution is as follows: `desired_list = [tuple(list(tup)+[value]) for tup in tuple_list]` – jason Mar 15 '18 at 17:20
  • To get the correct list of tuples solution, you can avoid multiple casts by doing `desired_list = [(value,)+v for v in tuple_list]` – F1Rumors May 07 '20 at 11:49
2

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

new_list = map(lambda x: [111] + list(x), tuple_list)
sashkello
  • 17,306
  • 24
  • 81
  • 109
  • List comprehensions are considered more Pythonic than `map`+`lambda`. – Amber Jan 29 '14 at 05:50
  • Isn't map + lambda faster tho? – Chris Jan 29 '14 at 05:50
  • @Amber No one knows what "pythonic" means any more. This is just another alternative, which could be faster, could be slower, but a viable solution... Some people love lambdas and maps and filters... I love list comprehensions and generators, but it has nothing to do with the validity of the answer :) – sashkello Jan 29 '14 at 05:52
  • "pythonic"? Isn't it time that phrase was retired? The list comp is generally easier to understand in my view, but the lambda is a perfectly reasonable approach. – Jon Kiparsky Jan 29 '14 at 05:53
  • @Chris I doubt there is any difference. Please see this question: http://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map – sashkello Jan 29 '14 at 05:54
1

Use map.

>>> tuple_list = [('a','b'),('c','d'),('e','f')]
>>> map(list, tuple_list)
[['a', 'b'], ['c', 'd'], ['e', 'f']]

Or a list comprehension.

>>> [list(elem) for elem in tuple_list]
[['a', 'b'], ['c', 'd'], ['e', 'f']]

Since your desired output is a list of tuples, you can do.

>>> [(111,) + elem for elem in tuple_list]
[(111, 'a', 'b'), (111, 'c', 'd'), (111, 'e', 'f')]
Sukrit Kalra
  • 33,167
  • 7
  • 69
  • 71