Two assignments in one python list view

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 an understanding of lists into one (if possible) if the size of a is large? If so, how do you do it?

Something like,

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

which does not work. If using list comprehension is not more computationally efficient than using a normal loop, let me know. Thanks.

+7
source share
2 answers

If you doubt the efficiency of using the timeit module, it is always easy to use:

 import timeit def f1(aRange): x = [2*i for i in aRange] y = [3*i for i in aRange] return x,y def f2(aRange): x, y = zip(*[(2*i, 3*i) for i in aRange]) return x,y def f3(aRange): x, y = zip(*((2*i, 3*i) for i in aRange)) return x,y def f4(aRange): x = [] y = [] for i in aRange: x.append(i*2) y.append(i*3) return x,y print "f1: %f" %timeit.Timer("f1(range(100))", "from __main__ import f1").timeit(100000) print "f2: %f" %timeit.Timer("f2(range(100))", "from __main__ import f2").timeit(100000) print "f3: %f" %timeit.Timer("f3(range(100))", "from __main__ import f3").timeit(100000) print "f4: %f" %timeit.Timer("f4(range(100))", "from __main__ import f4").timeit(100000) 

The results seem consistent, indicating the first option as the fastest.

 f1: 2.127573 f2: 3.551838 f3: 3.859768 f4: 4.282406 
+9
source

You want to use zip() built-in with a star-like operator for this. zip() usually turns into lists in a list of pairs, when it is used, it is unpacked - iterates over the list of pairs and splits 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) 

Please note that I'm not sure if this is really more efficient, as it matters.

+12
source

All Articles