Python: List Comprehensions

"A magical way of crafting arrays? Wow!"

List Comprehensions (LC for short) are one of those things I wish I had this 30 years ago while I was in Uni. In Python a "list" is just another name for an "array".

A List Comprehension is a function that applies to all elements in a list. You can filter those elements you want to apply the function to with conditions. The result is another list.

Example Let's imagine you have an array A with integer numbers. To copy the even numbers only to an array B, you could write:

B = [ i for i in A if (i % 2 == 0) ]

The syntax looks a bit confusing because there are no separators between the components of an LC, but there are three parts to it:

1) The return value: in the example above the return value is the first "i": [ i for i in A if (i % 2 == 0) ]
2) The iterator: works like other iterators and will evaluate every item "i" in the array A: [ i for i in A if (i % 2 == 0) ]
3) The condition: here we test if "number modulo 2" is equal to zero (this is a basic test for even numbers). When this condition returns "True", the return value is in (1) above: [ i for i in A if (i % 2 == 0) ]

B will look like [ 2, 4, 6, 8, ... etc ] -as we are filtering out odd numbers, B would be equal to about half the length of A

And that's it. That's all the mystery about List Comprehensions.

You'd be wise to test anything you find in the Internet before you use it.
"Elegant code does not exist; it either solves a business problem or it does not."