List comprehension Problem- with Python Solution

Lets say you have a list stored in a variable a = [ 12,3,45,6,6,45,123,345,67,78,43,23,567,87,9,23,8,4]. You are required to write only one line of python code that is able to generate a new list that contains only even numbers.

The simple iterative solution is like this

#   Program to find and display all the even numbers present in a list
#   program by          : rakesh kumar
#   website             : https://cbsetoday.com

# Let’s say a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. 
# Write one line of Python that takes this list a and makes a new list 
# that has only the even elements of this list in it.

a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
b = []
for x in a:
    if x%2==0:
       b.append(x)
print(b)

The problem of the above approach is: it used 4 lines to generate the solution.  Here is its optimized solution

#   Program to find and display all the even numbers present in a list
#   program by          : rakesh kumar
#   website             : https://cbsetoday.com

# Let’s say a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. 
# Write one line of Python that takes this list a and makes a new list 
# that has only the even elements of this list in it.

a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
b = [x for x in a if x%2==0 ]
print(b)

Hope you would like this concept and if you are able to find any bug or have other solution, please let us know, we would love to add your solution with full credit to you.

Related Posts

If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to contribute@cbsetoday.com See your article appearing on the cbsetoday.com main page and help other students/teachers.