Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two assignments in single python list comprehension

For example:

a = [1,2,3]
x = [2*i for i in a]
y = [3*i for i in a]

Would it be more efficient to combine the list comprehensions into one (if possible) if the size of a is large? If so, how do you do this?

Something like,

x,y = [2*i, 3*i for i in a]

which doesn't work. If using list comprehension is not more computationally efficient than using a normal for loop, let me know too. Thanks.

like image 990
user1473483 Avatar asked Jun 21 '12 22:06

user1473483


People also ask

Can you do assignment in list comprehension?

Using Assignment Expressions in List Comprehensions. We can also use assignment expressions in list comprehensions. List comprehensions allow you to build lists succinctly by iterating over a sequence and potentially adding elements to the list that satisfy some condition.

Can you add else in list comprehension Python?

Answer. Yes, an else clause can be used with an if in a list comprehension. The following code example shows the use of an else in a simple list comprehension.


1 Answers

You want to use the zip() builtin with the star operator to do this. zip() normally turns to lists into a list of pairs, when used like this, it unzips - taking a list of pairs and splitting into two lists.

>>> a = [1, 2, 3]
>>> x, y = zip(*[(2*i, 3*i) for i in a])
>>> x
(2, 4, 6)
>>> y
(3, 6, 9)

Note that I'm not sure this is really any more efficient in a way that is going to matter.

like image 77
Gareth Latty Avatar answered Oct 19 '22 23:10

Gareth Latty