This time you'll look at list comprehension in Python. Where the ternary conditional operator shortens an assignment with an if-else choice, list comprehension shortens an assignment of list data with a for loop.
Let's go further...
How do you use it, and how does it work? Let's go further…
List Comprehension in Python
As mentioned earlier, list comprehension is a ternary operator in Python whose job is to shorten the process of initializing a list variable.
Sometimes a case forces you to fill the elements of a list before you manipulate the data. You can certainly do that with a for loop and a list append on every iteration. Here's an example:
list = []
for i in range(10):
list.append(i)
print(list)
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Logically that way isn't wrong, but... Python already has a shorter method, and a more human one, than the approach above. This is where list comprehension shines 😎
If you ever studied set notation in math, list comprehension may already look familiar. Remember how to read this?
That notation reads:
listis the set of numbersx, such thatxis a whole number greater than or equal to 0 and less than 10.
That notation is in fact exactly like the code you built earlier. Namely, putting the set of whole numbers between 1 and 10 into the list variable.
So instead of getting confused, let's head back to the Python world.
How to Write List Comprehension
Because list comprehension is also a ternary operator, it needs 3 operands and 2 operators.
<variable-target> = [<kembalian> for <item> in <iterable>]
variable-target: the variable that holds the list you builtkembalian: the value returned as a list element. It can be a fixed value, a variable, or an expression that processes the value ofitemitem: holds the value from the iterable on each iteration, and you can use it as an expression in the return partiterable: a variable that holds a collection of values (list, string, tuple, etc.)
You can also add a condition:
<variable-target> = [<kembalian> for <item> in <iterable> if <kondisi>]
If there is an if statement like the format above, then the value of item is processed only when kondisi is True
Using List Comprehension
First you'll change the earlier code so it uses list comprehension. With the same logic, that code can be changed into this:
list = [i for i in range(10)]
print(list)
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Look at that. The code that had 4 lines now has only 2. With list comprehension, the initialization and the filling of the list variable happen at once, without a for loop and append.
What is actually happening?
To make the mechanism easier to follow, let's go through the initialization of the list variable from the innermost layer out.
for i in range(10): an ordinaryforloop, which means you take every element from the iterable (range(10)) and put it into the variablei[i for i in range(10)]: the value inside the variableibecomes the return expression for the list element. The return process then runs as many times as the length of the iterable, so you get a listlist = [i for i in range(10)]: the result of the list comprehension goes into the variablelist
Now let's try another example.
Building a list of squared numbers
In this case you'll build a list variable holding the first 10 squared numbers (starting from 0). To do it, you only need to change the return expression, until it becomes this:
list = [i*i for i in range(10)]
print(list)
Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
There you can see which part needed changing. Where you returned the value i before, you now return i*i, so you get a list of numbers to the power of 2.
Remember! The return value in list comprehension is an expression. So any data processing can happen there (including function calls and the ternary conditional operator).
Using a condition
Now let's add another case. How do you build a list holding the squared numbers of even numbers only? The final result would be 4, 16, 36, and so on.
To do this you can use an if block like the 2nd format. It will check whether the value of i is even or not. So the code changes into this:
list = [i*i for i in range(10) if i % 2 == 0]
print(list)
Output:
[0, 4, 16, 36, 64]
In that example the resulting list has a length of 5, unlike the earlier one with a length of 10. The cause is that the return expression only runs when the condition is True. So when i is odd, its value is never returned.
Building a list of the same value (constant)
List comprehension also works for initializing a list where every element holds the same value. Say a case asks you to build a list of 10 elements containing the same person's name. You can solve that with the code below:
names = ["inva" for x in range(10)]
print(names)
Output:
['inva', 'inva', 'inva', 'inva', 'inva', 'inva', 'inva', 'inva', 'inva', 'inva']
In that example the variable x isn't used at all in the return expression. The variable x only serves as a helper to drive the iteration.
Turning a sentence into a list of characters
Last example. You remember that a string in Python is also iterable, right? Because it's iterable, a string can be used for list comprehension too.
Say this case asks you to take every character from a string and put them into the list chars. Then the code looks like this:
sentence = "belajar python bareng inva"
chars = [char for char in sentence]
print(chars)
Output:
['b', 'e', 'l', 'a', 'j', 'a', 'r', ' ', 'p', 'y', 't', 'h', 'o', 'n', ' ', 'b', 'a', 'r', 'e', 'n', 'g', ' ', 'i', 'n', 'v', 'a']
You can actually change a string into a list with type casting. Example:
list(sentence)
Closing
That's all for this one, and I hope it's useful 😃
Next time you'll start playing with functions and sub programs in Python 3.
See ya…👋