Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 541
Asad Saeeduddin Avatar asked Mar 20 '13 22:03

Asad Saeeduddin


1 Answers

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]
like image 52
dawg Avatar answered Oct 01 '22 04:10

dawg