Search code examples
pythongeneratorlist-comprehension

Comprehensions: multiple values per iteration


Is there a way to output two (or more) items per iteration in a list/dictionary/set comprehension? As a simple example, to output all the positive and negative doubles of the integers from 1 to 3 (that is to say, {x | x = ±2n, n ∈ {1...3}}), is there a syntax similar to the following?

>>> [2*i, -2*i for i in range(1, 4)]
[2, -2, 4, -4, 6, -6]

I know I could output tuples of (+i,-i) and flatten that, but I was wondering if there was any way to completely solve the problem using a single comprehension.

Currently, I am producing two lists and concatenating them (which works, provided the order isn't important):

>>> [2*i for i in range(1, 4)] + [-2*i for i in range(1, 4)]
[2, 4, 6, -2, -4, -6]

Solution

  • Another form of nested comprehension:

    >>> [sub for i in range(1, 4) for sub in (2*i, -2*i)]
    [2, -2, 4, -4, 6, -6]