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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With