How to Create a List Comprehension in Python in One Line?

Estimated read time 2 min read

List comprehension is a concise and elegant way of creating a new list by performing some operations on an existing list. It allows you to create a list in a single line of code, making your code more readable and efficient. Here is how you can create a list comprehension in Python in one line:

Syntax:

new_list = [expression for item in iterable if condition]
  • new_list: The new list that will be created using list comprehension
  • expression: The operation or transformation to perform on each item in the iterable
  • item: The element of the iterable that will be transformed
  • iterable: The existing list or other iterable object
  • condition (optional): A condition that must be met for the item to be transformed and added to the new list.

Example:

# Create a new list of squares of numbers from 1 to 10
squares = [x*x for x in range(1, 11)]

# Create a new list of even numbers from an existing list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [x for x in numbers if x % 2 == 0]

In the first example, a new list of squares of numbers from 1 to 10 is created in a single line using list comprehension. In the second example, a new list of even numbers is created from an existing list by filtering out odd numbers using a condition in the list comprehension.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply