Concepts: multiple values ​​per iteration

Is there a way to output two (or more) elements for each iteration in a list / dictionary / set view? As a simple example, to output all positive and negative doublings of integers from 1 to 3 (i.e. {x | x = ±2n, n ∈ {1...3}}) is there a syntax like the following?

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

I know that I can output tuples (+i,-i)and smooth it out, but I was wondering if there is a way to completely solve the problem using one understanding.

I am currently creating two lists and merging them (which works if the order is not important):

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

Another form of nested understanding:

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

Another option is a nested understanding:

r = [2*i*s for i in range(1, 4) for s in 1, -1]

:

r = [item for tpl in (<something that yields tuples>) for item in tpl]

:

r = [item for tpl in ((2*i, -2*i) for i in range(1, 4)) for item in tpl]

itertools.chain.from_iterable, @Lattyware.

+6

- itertools.chain.from_iterable(), , , :

itertools.chain.from_iterable((2*i, -2*i) for i in range(1, 4))

( , , ).

+4

itertools, @Lattyware, , .

>>> def nums():
        for i in range(1, 4):
            yield 2*i
            yield -2*i


>>> list(nums())
[2, -2, 4, -4, 6, -6]
+4

PEP202, :

- [x, y for ...] ;       [(x, y) for ...].

+1

All Articles