List comprehensions in Python can be tricky and hard to look at but once you know the secret, it will become very clear, for example, say we have a list:
a = [1, 2, 3, 4, 5]
And we want to make a second list out of this “b” with values of “a” plus 2, so we want to get this:
b = [3, 4, 5, 6, 7]
Now, the way to do this without using any fancy feature would be:
b = [] for item in a: b.append(item + 2)
To turn this into a list comprehension we will start like this:
b = [for item in a]
Now, we will have to add our “item + 2″ to the left side of the for loop so:
b = [item + 2 for item in a]
If you didn’t understand what happened, don’t worry, just keep reading.
Now, let’s look at another example, this time, we will try to understand a list comprehension that’s already written, a very simple one:
a = [1, 2, 3, 4, 5] b = [x*x*x for x in a]
To read this, start form right to left:
for x in a: x*x*x
Internally, this will be translated to something like:
b = [] for x in a: b.append(x*x*x)
So the secret is to read from right to left.
If there should be a condition, it will come after the for loop so to increment all the items that are greater than 4 by 2:
b = [item + 2 for item in a if item > 4]
I hope this helps
Hamid Alipour is a partner in Codehead, LLP with his wife, Tess. Hamid speaks 12 markup and programming languages [Yes, 12: PHP, CSS, Ajax, JavaScript, HTML/XHTML, Java, Python, C/C++, ASP, Visual Basic, Scheme and Action Script]; has a penchant for solving the unsolvable; an affinity for clean, hand-written code and is a Zend Certified 