PadhaiTime Logo
Padhai Time

List Comprehensions

List Comprehension is a way of creating a list from any iterable. Iterable is something which can be iterated upon. List, Set, Tuple are some examples of Iterables. Items of an iterable can be iterated one by one and we can apply some transformation or calculation on the iterated value and finally the processed values become the part of a new list.

  

This way of manipulation and forming a new list is called List Comprehension.

 

Syntax: New_List = [ expression for item in Iterable]

 

List Comprehensions are helpful in solving many types of problem statements. Let us just check some of them.

 

 

Problem 1: Provided the below input, how can we generate the expected output using List comprehension?

Input: [ 1, 2, 3, 4, 5 ]

Output: [ 1, 4, 9, 16, 25 ]

 

Solution:

Input_lst = [ 1, 2, 3, 4, 5 ] 
New_list = [ item*item for item in Input_lst ]
print(New_list)

 

 

Problem 2: Provided the below input, how can we generate the expected output using List comprehension?

Input: [ 1, 2, 3, 4, 5 ]

Output: [ 1, 3, 5 ]

 

Solution:

Input_lst = [ 1, 2, 3, 4, 5 ]
New_lst = [ item for item in Input_lst if item%2 !=0 ] 
print(New_lst)

 

 

Problem 3: Provided the below input, how can we generate the expected output using List comprehension?

Input: [ 1, 2, 3, 4, 5 ]

Output: [ ‘odd’, ‘even’, ‘odd’, ‘even’, ‘odd’ ]

 

Solution:

Input_lst = [ 1, 2, 3, 4, 5 ]
New_lst = [ "even" if item%2 == 0 else "odd" for item in Input_lst ] 
print(New_lst)

 

 

Problem 4: Provided the below input, how can we generate the expected output using List comprehension?

Input: [ [1, 2], [3, 4] ] 

Output: [ 2, 4 ]

 

Logic:

Input_lst = [ [1, 2], [3, 4] ] 
New_lst = [value for item in Input_lst for value in item if value%2 ==0]
print(New_lst)

 

 

Problem 5: Provided the below input, how can we generate the expected output using List comprehension?

Input: [ [1, 2], [3, 4] ] 

Output: ['1_odd', '2_even', '3_odd', '4_even']

 

Logic:

Input_lst = [ [1, 2], [3, 4] ] 
New_lst = [str(value) + "_even" if value%2 ==0 else str(value)+ "_odd" for item in Input_lst for value in item]
print(New_lst)

Bengaluru, India
contact.padhaitime@gmail.com
  • We collect cookies and may share with 3rd party vendors for analytics, advertising and to enhance your experience. You can read more about our cookie policy by clicking on the 'Learn More' Button. By Clicking 'Accept', you agree to use our cookie technology.
    Our Privacy policy can be found by clicking here