In this blog, we will learn how to create a list in python with a list comprehension. We have seen the formal way to create lists in python using
list() function and the manual way i.e .
Let’s First take a look how we create list in python.
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.
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)
[1, 2, 3, 4, 5] ['Hello', 'world']
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.
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)
[1, 2, 3, 4, 5]
Learn about Python Web Scraping to CSV.
Python List Comprehension
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.
[expression for item in iterable]
num_list = [number for number in range(1, 10)] print(num_list)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
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.
list_num =  for num in range(0,10): list_num.append(num) print(list_num)
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.
num_list = [number**2 for number in range(1, 10)] print(num_list)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
number**2 – This expression makes a list of squares of numbers between 1 to 10 (excluding 10).
Python List Comprehension if-else Condition
[expression for item in iterable if condition]
Let’s play with some condition now. This time we want to store all the even numbers between 1 – 10.
num_list = [number for number in range(1, 10) if number % 2 == 0] print(num_list)
[2, 4, 6, 8]
If we did it the traditional python way, it would look like:
list_num =  for num in range(0,10): if num % 2 == 0: list_num.append(num) print(list_num)
List Comprehension makes it compact.
Python List Comprehension Nested Loop
Let’s print a list of tuples using the List Comprehension.
Traditional way would look like this:
for i in range(0, 3): for j in range(0, 3): print((i, j))
List Comprehension Way:
num_list = [(i, j) for i in range(0, 3) for j in range(0, 3)] for cell in num_list: print(cell)
(0, 0) (0, 1) (0, 2) (1, 0) (1, 1) (1, 2) (2, 0) (2, 1) (2, 2)
Hope you like it!