Thursday 11 June 2020

List Comprehensions in Python

Getting started with List comprehensions in Python

List Comprehensions provide a concise and elegant way to create new lists based on the

existing lists or other iterable. List Comprehensions has a variable that iterates over existing list using

for-loop and conditional statements.

Note: conditional statements may or may not be present in the List Comprehensions.

 

Syntax to construct List Comprehensions in Python:

new_list = [variable  for variable in old_list if condition]


Without Conditional Statement:

Suppose, you want to create a list with each element is square of each element of existing list

exist_list = [1, 2, 3, 4, 5, 6, 7, 8]

squared_list = [var**2 for var in exist_list]

print(squared_list)

Output: [1, 4, 9, 16, 25, 36, 49, 64]

 

Using Conditional Statement in List comprehensions:

Now, you want to create a list with each element is multiple of 5 from an existing list

exist_list = [1, 5, 6, 10, 14, 15, 25, 30] 

is_multiple_of_five = [var for var in exist_list if var % 5 == 0 ]

print(is_multiple_of_five)

Output: [5, 10, 15, 25, 30]

 

 

 

 

16 comments: