Time for a list comprehensions drill. In the previous two articles we were talking about list comprehensions. Let’s practice them now.
But before you start, make sure to read the article on list comprehensions and the article on matrix operations with list comprehensions if you haven’t done so yet.
OK, in this list comprehensions drill I’ll ask you to code 3 list comprehensions. Maybe they don’t seem extremely useful, but maybe there are some use cases for them out there. Anyway, let’s say it’s just for practice.
Try to do each exercise yourself before checking the solution.
Table of Contents
Exercise 1
The first one is about numbers. We want a list of all the numbers from 1 to 100 whose last digit is 1.
So, this is what we want to get:
[1, 11, 21, 31, 41, 51, 61, 71, 81, 91]
HINT: In order to check if a number ends in a specific digit, you can convert it to a string and use the endswith method.
Solution to Exercise 1
And here’s the solution:
>>> [x for x in range(1, 101) if str(x).endswith('1')]
[1, 11, 21, 31, 41, 51, 61, 71, 81, 91]
Exercise 2
OK, the second example:
Here we have a string:
a = "insane"
We want to make the following list:
['Insane', 'Insan', 'Insa', 'Ins', 'In', 'I']
HINT: Make use of slicing and use the range function with a negative step. And don’t forget to capitalize the first letter in each string. There’s a string method you can use to do that.
Solution to Exercise 1
OK, and here’s the solution:
>>> [a[:n].capitalize() for n in range(len(a), 0, -1)]
['Insane', 'Insan', 'Insa', 'Ins', 'In', 'I']
Exercise 3
Finally, our last example. A slightly trickier one.
We have a matrix defined as a list of lists:
A = [[5, 7, 4],
[8, 2, 1],
[7, 5, 3],
[6, 4, 9]]
As you can see, it’s not a square matrix, but it doesn’t matter. What we want to make is a matrix in which each number is replaced by the greatest number in its row. So, the matrix should look like this:
[[7, 7, 7], [8, 8, 8], [7, 7, 7], [9, 9, 9]]
HINT: You can use the built-in max function to find the greatest number in each row.
Solution to Exercise 1
And here’s the solution:
>>> [[max(row) for i in row] for row in A]
[[7, 7, 7], [8, 8, 8], [7, 7, 7], [9, 9, 9]]
These were just a couple of examples, maybe not the most useful ones, but list comprehensions are powerful and fast tools which are used all the time, so make sure you get familiar and befriended with them 🙂
Here’s the video version of the article: