List Comprehension

List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.

The Syntax

newlist = [expression for item in iterable if condition == True]

The return value is a new list, leaving the old list unchanged.

Condition

The condition is like a filter that only accepts the items that valuate to True.

Iterable

The iterable can be any iterable object, like a list, tuple, set etc.

Expression

The expression is the current item in the iteration, but it is also the outcome

Example

Based on a list of fruits, you want a new list, containing only the fruits with the letter “a” in the name.

Without list comprehension you will have to write a for statement with a conditional test inside:

1
2
3
4
5
6
7
8
fruits=["apple","banana","cherry","kiwi","mango"]
newlist1=[]

for x in fruits:
if 'a' in x:
newlist1.append(x)

print(newlist1)

Two-dimensional array

Before that we should create one-dimensional array firstly.

1
2
3
4
5
6
arr1=[0 for x in range(10)]
print(arr1)
arr2=[x for x in range(10)]
print(arr2)
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Now, we can create two-dimensional arrays based on one-dimensional arrays.

1
2
3
4
5
6
7
arr1=[[0 for x in range(10)] for x in range(2)]
print(arr1)
arr2=[[x+(i*10) for x in range(10)] for i in range(2)]
print(arr2)
# [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
# [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]]