Python List Comprehension

List comprehensions in python are a short-hand way to create lists based on intelligent logic.

For example, let’s generate all the even numbers from 0 to 15 in one line:

[x for x in range(15) if x % 2 == 0]
#Output: [0, 2, 4, 6, 8, 10, 12, 14]

Note that range() returns a sequence. You could just have easily listed [0,1,2,3…] and gave it a direct list or a list from earlier in your code.

You can have multiple for clauses. Each one can run over a different source list. You’ll end up with the Cartesian product though. For example:

[(x,y) for x in range(3) for y in range(2)]
#Output: [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]

In these results you’ll notice we had x going exclusively up to 3 and y going exclusively up to 2. So, we end up with 6 results. If we had x and y as large numbers, it would be a very big result. We could have any number of for clauses, so the result list could get large fast.

Also notice that we didn’t have to have any if’s for filtering. If’s, like for’s can have any number. So, this is also valid:

[x for x in range(15) if x % 2 == 0 and x not in [2,4,6]]
#Output: [0, 8, 10, 12, 14]

In this case, we filtered it down to even numbers in the first if, and then filtered out some predefined numbers using the not in operator (which is very cool in itself for a language).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s