4

I have a list of tuples where one of the elements in the tuple is a list.

example = [([0, 1, 2], 3, 4), ([5, 6, 7], 8, 9)]

I'd like to end up with just a list of tuples

output = [(0, 1, 2, 3, 4), (5, 6, 7, 8, 9)]

This question seems to address the issue with tuples but I am concerned as my use case has many more elements in the inner list and

[(a, b, c, d, e) for [a, b, c], d, e in example]

seems tedious. Is there a better way to write this?

Community
  • 1
  • 1
o-90
  • 17,045
  • 10
  • 39
  • 63

3 Answers3

5

Tuples can be concatenated with + like lists. So, you can do:

>>> example = [([0, 1, 2], 3, 4), ([5, 6, 7], 8, 9)]
>>> [tuple(x[0]) + x[1:] for x in example]
[(0, 1, 2, 3, 4), (5, 6, 7, 8, 9)]

Note that this works in both Python 2.x and 3.x.

4

In Python3 you could also do:

[tuple(i+j) for i, *j in x]

if you don't want to spell out each part of your input

junnytony
  • 3,455
  • 1
  • 22
  • 24
2

If writing a function is an option:

from itertools import chain

def to_iterable(x):
    try:
        return iter(x)
    except TypeError:
        return x,

example = [([0, 1, 2], 3, 4), ([5, 6, 7], 8, 9)]
output = [tuple(chain(*map(to_iterable, item))) for item in example]

Which gives:

print(output)
[(0, 1, 2, 3, 4), (5, 6, 7, 8, 9)]

It's way more verbose than the other solutions, but has the neat advantage of working no matter the position or number of lists in the inner tuples. Depending on your requirements this might be overkill or a good solution.

ereOn
  • 53,676
  • 39
  • 161
  • 238