November 27, 2021•5 min read

List Comprehension in Python

List comprehension is the ternary operator in Python that shortens the process of initializing a list variable.

Read in Indonesian

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:

PYTHON
list = []
for i in range(10):
    list.append(i)

print(list)

Output:

TEXT
[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?

list=x∣0≤x<10,x∈Zlist = {x | 0 \le x \lt 10, x \in \Z }

That notation reads: list is the set of numbers x, such that x is 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.

TEXT
<variable-target> = [<kembalian> for <item> in <iterable>]
  • variable-target: the variable that holds the list you built
  • kembalian: the value returned as a list element. It can be a fixed value, a variable, or an expression that processes the value of item
  • item: holds the value from the iterable on each iteration, and you can use it as an expression in the return part
  • iterable: a variable that holds a collection of values (list, string, tuple, etc.)

You can also add a condition:

TEXT
<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:

PYTHON
list = [i for i in range(10)]
print(list)

Output:

TEXT
[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.

  1. for i in range(10): an ordinary for loop, which means you take every element from the iterable (range(10)) and put it into the variable i
  2. [i for i in range(10)]: the value inside the variable i becomes 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 list
  3. list = [i for i in range(10)]: the result of the list comprehension goes into the variable list

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:

TEXT
list = [i*i for i in range(10)]
print(list)

Output:

TEXT
[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:

PYTHON
list = [i*i for i in range(10) if i % 2 == 0]
print(list)

Output:

TEXT
[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:

PYTHON
names = ["inva" for x in range(10)]
print(names)

Output:

TEXT
['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:

PYTHON
sentence = "belajar python bareng inva"
chars = [char for char in sentence]
print(chars)

Output:

TEXT
['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…👋

Get better at shipping code.

Join the other developers getting tech updates, tips, and relaxed tutorials in their inbox every week.

Stay in the loop

Tech updates, coding tips, and relaxed insights straight to your inbox every week.

No spam. Unsubscribe anytime.

Read next

See all
Struktur DataWhat a Linked List Actually Is

A linked list is a linear chain of nodes, each holding data and a pointer to the next node. Here is what that chain looks like, what it costs next to an array, and the same minimal implementation in Java, Python, and JavaScript.

For developers who learn by struggling

© 2026 Inva.dev.