Introduction
If you are already familiar with Python Lists and its basics, then one more thing you need to learn related to this topic is List Comprehension in Python. List comprehension is one of the exclusive features of Python Language which helps to write code in a compact form or fewer lines.
The Syntax
new_list = [expression for item in iterable]
or
new_list = [expression for item in iterable conditional statement]
Example 1
We will start learning this topic with several programming examples. To give you a better idea of this, I have chosen a problem that I will first solve using traditional way; next, we'll solve the same problem but using list comprehension. Let's start with a simple one.
Problem: Store all the even numbers from a given list to a new list.
Without list comprehension
num = [1,2,3,4,5,6]
new_list = []
for i in num:
if i%2==0:
new_list.append(i)
print(new_list)
Using List Comprehension
Now see, how to solve the above problem using list comprehension method and here is the difference.
num = [1,2,3,4,5,6]
new_list = [i for i in num if i%2==0]
print(new_list)
Output
[2, 4, 6]
Example 2
Let's solve two more similar problems.
Problem 1: Store squares of all the numbers between 1 to 10 in a list using list comprehension method.
square = [i**2 for i in range(1,11)]
print(square)
Output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Problem 2: Store the first letter of every word from a given list to a new list using the list comprehension method.
names = ['PySeek', 'Python', 'List', 'Comprehension']
new_list = [name[0] for name in names]
print(new_list)
Output
['P', 'P', 'L', 'C']
List comprehension with two conditions
So far we have solved multiple problems but they were pretty straightforward. Let's make it a little conditional. Here, we will add multiple conditions to the list comprehension statement.
Problem: Iterate through a list of integer numbers; if the number is even, then square of it and store in another list, else store the number as a negative form. Solve this problem using only the list comprehension method.
Numbers = [1,2,3,4,5,7,8,9,10,11,12,13,14,15,16]
newList = [i**2 if (i%2==0) else -i for i in Numbers]
print(newList)
Output
[-1, 4, -3, 16, -5, -7, 64, -9, 100, -11, 144, -13, 196, -15, 256]
Nested list comprehension in python
A nested loop is a loop inside another loop and the parent loop can have any number of child loops. To show you an example, I have taken a simple problem where one for loop is within another for loop and the result will be stored in a python list using the list comprehension method.
nested_comp = [[i for i in range(1,5)] for j in range(4)]
print(nested_comp)
Output
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]