Suppose, you have a task, you have to separate the letters of the word hello and add the letters as items of a list. The first thing that comes in your mind would be using for loop. and you can complete the task like that:

letters = []

for letter in 'hello':
    letters.append(letter)

print(letters)

When you run the program, the output will be:

[‘h’, ‘e’, ‘l’, ‘l’, ‘o’]

However, Python has an easier way to solve this issue using List Comprehension and it’s an elegant and simple (personal opinion) way.


Syntax of List Comprehension

[expression for item in iterable (string, list, set, dictionary)]

Let’s see how the above program can be written easily using list comprehension.

letters = [ letter for letter in 'hello' ]
print(letters)
List Comprehension Python

Here; first of all we create a variable letters and in this variable, we assign a list and in this list, we create a variable letter (1st one) and then we create a regular for loop, like that – for letter in ‘python’.

last of all we print the variable – letters.

When you run the above program, the output will be:

[‘h’, ‘e’, ‘l’, ‘l’, ‘o’]

Tags: