Previous Lesson: Lesson 19: List Slices in Python
Learn how to use our mathematical-pythonic skills to quickly create lists that obey a simple rule using list comprehensions in Python.
Why is this important? Python is famous for allowing you to write code that’s elegant, easy to write, and almost as easy to read as plain English. We can use list comprehensions to create powerful functionality within a single line of code.
Anyway, let’s start. Create a new file: ex17.py. And type this in:
We haven’t talked about for before. But we’ll discuss that next time. For now, you’ll just need to bear in mind that it’s used for looping. Just like what we’ve learned in Lesson 15, the range(5) produces: [0, 1, 2, 3, 4]. (You can try this.) But with the i**3 for , these integers will be multiplied thrice to itself, or cubed. So when we run it:
0³ = 0
1³ = 1
2³ = 8
3³ = 27
4³ = 64
That’s why it returns a [0, 1, 8, 27, 64].
List Comprehensions with ‘if’
Type this in:
We know that range(10) produces: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]. But! if i**2 % 2 == 0 says that when we divide the numbers inside our list to 2 (because it uses the modulo or the “%” symbol), the remainder should be equal to 0.
Therefore, this will give us only the even numbers: 0, 2, 4, 6, 8. And just like what you would have guessed, the i**2 for i just means that we will square these numbers, producing:
Did you get it?
Having very large numbers in list comprehensions
Look, I know that having big and being able to produce so many numbers could be a lot of fun. But, I gotta warn you that computers are limited, too in terms of their memory. Try this:
Let’s run this:
What happened? Exactly, nothing happens because the computer can’t take that much of a big number. And our Terminal will just keep looking like this so it would be a relief if we could stop this rubbish. Fortunately, we can do Ctrl + C or control + C:
So that’s it with List comprehensions in Python. You can do more experimenting on this one. Remember, though, that you have to be careful with the larger numbers. And always remember that if you have a question, I’m here to try my best to answer it. See you on the next lesson!
2 Replies to “Lesson 20. List Comprehensions in Python”