This is an extension of my blog article about list comprehensions and the first part of an advanced python series. We will cover List Comprehensions, Lambdas, Functional Programming, Map / Reduce / Filter, Decorators, and Descriptors.
Python List Comprehensions
List comprehensions are Python's solution to the large loops required to do tasks which should be easy. They transform the simple task of getting all the even numbers between zero and one-thousand from:
my_list = []
for index in range(1000):
if index % 2 == 0:
my_list.append(index)
to
my_list = [x for x in range(1000) if x % 2 == 0]
The use for list comprehensions
List comprehensions are essentially:
list_name = [expression values filter]
Values - A
for loop of values to check against the filter
Filter - All values go through this. It is an
if statement, and the expression is appended to the end of the list when it is true.
Expression - Data to append onto the list if Filter is true
It's important to note here that the expression could be anything. We could get the squares of all even numbers between zero and one-thousand just as easily:
my_list = [x**2 for x in range(1000) if x % 2 == 0]
Interesting Points
List comprehensions work on strings, and the
for loop can loop through any list. The expression can be as complex as you want. The expression is what gets appended, and it can even be another list. Look at this piece of code:
my_list = [[x*y for y in range(1,11) if y % 2 == 0] for x in range(1,11) if x % 2 == 0]
This generates a list of lists (which is stored in
my_list) where every even number between one and ten is multiplied by every other even number between one and ten.
Conclusion
To practice list comprehensions you can try out
Code Academy's interactive course. You can also learn more by looking at the
Python Docs List Comprehensions are a very useful tool which can replace many loops if you look out for it.
Cheers :)!
Article Update Log
June 20 2013 - Released Article
August 19 2013 - Added in Python Docs Link.
In my_list = [x**2 for x in range(1000) if x % 2 == 0]
What does x**2 mean?