Python – List Comprehension

List comprehension provides a concise and elegant way to create a new list by applying an expression to each item in an existing list. It offers a shorter and more readable syntax compared to traditional for loops. You can also include conditions to filter elements during the process. This makes list comprehension a powerful tool for transforming and filtering data in one line of code.

numbers = [1, 2, 3, 4, 5]
squared_numbers = [x ** 2 for x in numbers]

print("Squared List:", squared_numbers)

Do it

One Line Code

With list comprehension, you can do all that with only one line of code. It allows you to create a new list by looping through an existing one, applying an expression, and even adding a condition—all in a single, compact line. This makes your code shorter, cleaner, and often more efficient than using traditional for loops.

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [x for x in numbers if x % 2 == 0]

print("Even Numbers:", even_numbers)

Do it