Search code examples
pythontupleslist-comprehensioniterable-unpacking

Most Pythonic way to convert tuple to list, with new elements after each existing one


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.


Solution

  • 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)]