Intermediate Python Session Part 1 of 4

PEP 202 created list comprehensions to provide a better way to create lists using for and if clauses. The functionality of list comprehensions can be found in both map and filter functions.


For example, creating a list of integers as strings could be done imperatively in this manner (just like the map function):



Now, a list comprehension can create str_num in one line:



List Comprehensions not only have functionality of map, but also filter.


Here is an imperative example of filtering out the negative integers of a list:



And here is the same code in a list comprehension:


The Skeleton

Now, let’s breakdown the consisting parts of a list comprehension.

。Construct the for loop inside the [ ] bracket, with the Control Variable and Input Sequence.

。Create an Optional Operation expression if needed.

。Create Output Expression producing elements of the output of the xrange function membersof the Input Sequence that satisfy the Optional Operation


Variable Leaking

The only problem with list comprehensions in Python 2, is the control variable (i in the example below) shadows the i in the global scope:


When the list comprehension is executed the control variable will overwrite the the previous value. This issue has been resolved in Python 3, but yet to be fixed in Python 2. Just make sure when making global variables, don’t have it match the control variable in your list comprehensions.


Well, there is more to list comprehensions (like nested list comprehensions) than what I offered in this article. This is just an intro, to give you a basic understanding of list comprehensions.


The next my four part series of Intermediate Python will be on Generator Expressions.





 Jaime Gabriel Jingco

Software Engineer/ Applied Labs Assistant Instructor 

Check our Next Webinars


Recent Post