1

Question may be confusing, so here's an example:

I want to go from a tuple like (a, b, c) to a list of the form [a, 1, b, 1, c, 1]. What's the most Pythonic way to do this? I tried something like [*(x, 1) for x in list], before realizing that you can't unpack in list comprehension. What's the best way to do this? I already searched for a while and couldn't find anything helpful.

Spencer Lutz
  • 311
  • 1
  • 2
  • 14
  • 2
    Related: [How to make a flat list out of list of lists?](https://stackoverflow.com/q/952914/4518341) – wjandrea Jul 19 '20 at 03:59

2 Answers2

6

You can "unpack" in a list comprehension, but not quite like that. Use another loop.

xs = (a, b, c)
[e for x in xs for e in (x, 1)]
gilch
  • 10,813
  • 1
  • 23
  • 28
2

You could use itertools.chain.from_iterable:

>>> from itertools import chain
>>> t = ('a', 'b', 'c')
>>> list(chain.from_iterable((x, 1) for x in t))
['a', 1, 'b', 1, 'c', 1]

But personally I'd prefer the chained comprehension solution in glitch's answer

wjandrea
  • 28,235
  • 9
  • 60
  • 81