DEV Community

Divyanshu Shekhar
Divyanshu Shekhar

Posted on • Updated on

Python List Comprehension

List Creation

The below code is the normal way of creating a list in python and using the append function to append an element at the end of the list.

Python List

num_list = []
num_list2 = ['Hello', 'world']
num_list.append(1)
num_list.append(2)
num_list.append(3)
num_list.append(4)
num_list.append(5)

print(num_list)
print(num_list2)
Output:
[1, 2, 3, 4, 5]
['Hello', 'world']
Enter fullscreen mode Exit fullscreen mode

List Creation Using The List() Function
The list() function doesn’t take any argument and constructor creates an empty list and returns it. The list is then appended using the append function.

Python List using list() function

num_list = list()
num_list.append(1)
num_list.append(2)
num_list.append(3)
num_list.append(4)
num_list.append(5)

print(num_list)
Output:
[1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Python List Comprehension

In the above section, we took a brief look at the python list, now we will understand what is list comprehension in python.

In the above examples, we either first created an empty list or manually added the items. List Comprehension makes it easy for us.

Example:

[expression for an item in iterable]
Enter fullscreen mode Exit fullscreen mode
num_list = [number for number in range(1, 10)]

print(num_list)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Enter fullscreen mode Exit fullscreen mode

This would have taken 8-9 lines to add elements to a list or we would have used a loop that would have taken about 2 lines of code too. But Comprehension List can do that in only a single line.

Python List using loop

list_num = []
for num in range(0,10):
    list_num.append(num)

print(list_num)
Enter fullscreen mode Exit fullscreen mode

Comparing this example with the list comprehension, there the loop is directly placed in the square brackets and an expression sits before the loop that is basically what is stored in the list.

Example:

Change in Expression
num_list = [number**2 for number in range(1, 10)]

print(num_list)
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81]
Enter fullscreen mode Exit fullscreen mode

number**2 – This expression makes a list of squares of numbers between 1 to 10 (excluding 10).

Read the whole post Python List Comprehension from the original Post.

Top comments (0)