One of the thing that I like about the Python language is the level of versatility you have at your disposal. List comprehensions is concept that enables you to generate a list quickly with minimal code. At first glance, they appear confusing to read, but once the syntax is understood, they can prove to be very powerful. As I am a PHP developer first, I will make comparison syntax that will hopefully make things easier to understand.

In PHP we can generate a simple array like this;

$lang = array('PHP', 'Python', 'Ruby', 'Java');

Now say we wanted to alter that array making all of it’s values uppercase. We might do this;

$newLang = array();
foreach ($lang as $name) {
    $newLang[] = strtotupper($name);
}

Now, in Python using list comprehensions, we would do this;

lang = ['PHP', 'Python', 'Ruby', 'Java']
newLang = [name.upper() for name in lang]

Okay, that’s really simple yes? If it doesn’t make sense, read if from right to left, so ‘for name in lang’, then ‘name.upper()’. Let’s move on.

Say we wanted to do some string substitution. In PHP we may do this;

$lang = array('PHP', 'Python', 'Ruby', 'Java');
$newLang = array();
foreach ($lang as $name) {
	$newLang[] = sprintf('I like %s', $name);
}

Using list comprehension in Python it looks like this;

lang = ['PHP', 'Python', 'Ruby', 'Java']
newLang = ['I like %s' % name for name in lang]

See how elegant and easy it is? You can even expand on this and add conditionals too. The following example creates a new list if the language begins with the letter ‘P’.

lang = ['PHP', 'Python', 'Ruby', 'Java']
newLang = [name for name in lang if name[0] == 'P']

In PHP, we would do this to achieve the same result;

$lang = array('PHP', 'Python', 'Ruby', 'Java');
$newLang = array();
foreach ($lang as $name) {
	if (substr($name,0,1) === 'P') {
		$newLang[] = $name;
	}
}

To go one step further again, we can create the final list using two loops inside the comprehension. Take a look at this example;

gridx = range(0,5) # [0,1,2,3,4]
gridy = range(1,4) # [1,2,3]
mix = [[x, y] for x in gridx for y in gridy]

This outputs the following result;

[[0, 1], [0, 2], [0, 3], [1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3], [4, 1], [4, 2], [4, 3]]

In PHP, we would use two nested loops to create the same result;

$gridx = array(0,1,2,3,4);
$gridy = array(1,2,3);
$mix = array();
foreach ($gridx as $x) {
	foreach ($gridy as $y) {
		$mix[] = array($x,$y);
	}
}

And that’s pretty much all you need to know about Python list comprehensions. Their a great way of simplifying code and can be very expressive when wanting to generate lists. Have fun!

Advertisement