Grammar/Environments

[Python] How to Use Comprehension [List, Dictionary, if]

This article shows how to use comprehension.

Comprehension in Python provide us with a concise way to construct new sequences (such as list, set, dictionary etc.).

Contents

  • Basics of Comprehension
  • Combination of comprehension and if statement
  • Combination of comprehension and if-else statement
  • Combination of comprehension and enumerate() function
  • Combination of comprehension and zip() function
  • Dictionary comprehension

sponsored link

Basics of Comprehension

In the beginning, I explain briefly basics of comprehension.

Comprehension is often used to construct new list.

The syntax of list comprehension is as stated below.

How to write

[ expression for item in iterator ]

The syntax includes "for statement".

Elements are taken from iterable(list, tuple, etc.) and calculated based on "expression".

A new list is created from the calculation results.

This is an example code.

num_list = list(range(6))
print(num_list)
# [0, 1, 2, 3, 4, 5]

double_list = [num*2 for num in num_list]

print(double_list)
# [0, 2, 4, 6, 8, 10]

> double_list = [num*2 for num in num_list]

Elements are taken from "num_list" with the variable name "num" and multiplied by 2.

[ Supplement ] The same process without list comprehension.

num_list = list(range(6))
print(num_list)
# [0, 1, 2, 3, 4, 5]

double_list = []
for num in num_list :
    double_list.append(num*2)

print(double_list)
# [0, 2, 4, 6, 8, 10]

Use of comprehension allows for concise descriptions.

[ Supplement ] Combination of map( ) function and lambda.

num_list = list(range(6))
print(num_list)
# [0, 1, 2, 3, 4, 5]

double_list = map(lambda num : num*2, num_list)
print(list(double_list))
# [0, 2, 4, 6, 8, 10]

This method can also be described on a single line.

It is a matter of taste, but I think list comprehension is more concise.

How to use of map( ) function and lambda are explained in this article.

How to Use map( ) Function
How to Use Lambda

sponsored link

Combination of comprehension and if statement

Comprehension can be combined with if statement.

By using "if statement", a new list can be created using only elements that satisfy the condition.

How to write

[ expression for item in iterator if statement ]

This is an example code.

Only odd-numbered elements are doubled.

num_list = list(range(6))
print(num_list)
# [0, 1, 2, 3, 4, 5]

double_list = [num*2 for num in num_list if num%2 == 1]

print(double_list)
# [2, 6, 10]

> if num%2 == 1

Even and odd numbers are determined by whether the remainder divided by 2 is 1 or not.

This is another example code.

A new list is created with elements that contain certain letters.

fruits = ['Apple', 'Banana', 'Orange', 'Peach', 'Lemon']

fruits_new = [ fruit for fruit in fruits if 'n' in fruit]

print(fruits_new)
# ['Banana', 'Orange', 'Lemon']

> if 'n' in fruit

The "if statement" become True if the string contains "n".

Combination of comprehension and if-else statement

Comprehension can be combined with if-else statement.

The syntax of list comprehension with if-else statement is as stated below.

How to write

[ expression if-else statement for item in iterator ]

This is an example code.

By determining whether the elements of the original list are even or odd, a new list is created using the strings "odd" and "even".

num_list = list(range(6))
print(num_list)
# [0, 1, 2, 3, 4, 5]

num_types = ["odd" if num %2 == 1 else "even" for num in num_list]
print(num_types)
# ['even', 'odd', 'even', 'odd', 'even', 'odd']

sponsored link

Combination of comprehension and enumerate() function

I show combination of comprehension and enumerate( ) function.

By using the enumerate( ) function, the elements and indices of iterable objects (such as list, tuple, etc.) are got simultaneously.

This is an example code.

fruits = ['Apple', 'Banana', 'Orange', 'Peach', 'Lemon']

list_fruits = [(num, fruit) for num, fruit in enumerate(fruits) if 'n' in fruit]
print(list_fruits)
# [(1, 'Banana'), (2, 'Orange'), (4, 'Lemon')]

How to use of enumerate( ) function is explained in this article.

How to use of enumerate( ) function

Combination of comprehension and zip() function

I show combination of comprehension and zip( ) function.

The zip( ) function creates an iterator that will aggregate elements from multiple iterables.

This is an example code.

fruits = ['Apple', 'Banana', 'Orange', 'Peach', 'Lemon']
prices = [100, 200, 100, 200, 100]

list_fruits = [(fruit, price) for fruit, price in zip(fruits, prices) if 'n' in fruit]
print(list_fruits)
# [('Banana', 200), ('Orange', 100), ('Lemon', 100)]

How to use of zip( ) function is explained in this article.

How to use of zip( ) function

Dictionary comprehension

Dictionary can also be created by using comprehension.

Specify "key" and "value" in comprehension.

How to write

{ key : value for item in iterator }

This is an example code.

fruits_list = ['Apple', 'Banana', 'Orange']

fruits_dict = {fruit : len(fruit) for fruit in fruits_list}

print(type(fruits_dict))
# <class 'dict'>
print(fruits_dict)
# {'Apple': 5, 'Banana': 6, 'Orange': 6}

sponsored link

-Grammar/Environments
-