How to Create a List Comprehension Exercise in Python?

Estimated read time 1 min read

Sure, here’s an exercise to create a list comprehension in Python:

Exercise: Write a Python program that creates a new list of squares of even numbers from an existing list.

Input:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Output:

[4, 16, 36, 64, 100]

Solution:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# List comprehension to create a new list of squares of even numbers
squares_of_evens = [x*x for x in numbers if x % 2 == 0]

print(squares_of_evens)

In the above solution, we first create an input list numbers containing integers from 1 to 10. We then use a list comprehension to create a new list squares_of_evens containing the squares of even numbers in the input list. The if condition inside the list comprehension checks if the number is even or not, and only squares the even numbers. Finally, we print the squares_of_evens list to display the output.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply