Sunday, March 3, 2019

Python List Comprehension


One of the more Python'esk features of the language is list comprehension.  List comprehension is a means of transforming one list into another.  It's worth knowing, any list comprehension can readily be implemented by a for-loop but list comprehension is often considered more Python'ic.

So, why not simply use a for-loop?  Whelp, probably a couple reasons: 1) done right, a list comprehension can be more understandable, 2) it eliminates the need for locally scoped temporary variables.

Let's look at an example; taking a list of random numbers and returning a sublist of those that are even.



$ cat -n b
     1 #!/usr/bin/python
     2 import random
     3 
     4 L = random.sample(xrange(100), 10)
     5 print L;
     6 
     7 L0=[];
     8 for el in L:
     9   if el % 2 == 0:
    10     L0.append(el);
    11 print L0;
    12 
    13 L1=[el for el in L if el % 2 == 0];
    14 print L1;

Line 4 establishes a list of random numbers, 10 deep.
Lines 7-10 establishes L0, a sublist of all even numbers, preserving the order.
Line 13 performs the same effect, using list comprehension.
List comprehension is arguably much more readable.

Unlike the for-loop, the list comprehension doesn't suffer from a variable hanger-on, namely variable 'el'.  Often not an issue, but you happen to have this embedded in a series of statements you may quickly find a side-effect of overloading the variable name and the consequences that come along with it.


No comments:

Post a Comment