How to Write List comprehension [For loop] in Python

Write a program to generate list comprehension. One list should contain first 20 odd numbers and another should contain first 20 even numbers.

Python list comprehension
How to Code List Comprehension Python-Best Example


Here's logic to write list comprehension


#1: List comprehension to print odd numbers


lst1 = [x for x in range(40) if x % 2 != 0]
print('First 20 Odd Numbers:')
print(lst1)


#2: List comprehension to print even numbers


lst2 = [x for x in range(40) if x % 2 == 0]
print('First 20 Even Numbers:')
print(lst2)

Result: after run the Python scripts


First 20 Odd Numbers: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39]


First 20 Even Numbers: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38] 


** Process exited - Return Code: 0
** Press Enter to exit terminal

Related

Comments

Most Popular

7 AWS Interview Questions asked in Infosys, TCS

How to Decode TLV Quickly

Hyperledger Fabric: 20 Real Interview Questions