How to Create a List Comprehension in Python?

Estimated read time 2 min read

In Python, a list comprehension is a concise way to create a list. It consists of an expression followed by a for clause, and optionally one or more if clauses. Here’s the basic syntax:

new_list = [expression for item in iterable if condition]

In this syntax, new_list is the name of the new list that will be created. expression is the value that will be appended to the new list for each iteration. item is the current item in the iterable, and iterable is a sequence of values (e.g., a list, tuple, or range). condition is an optional boolean expression that filters the items in the iterable.

Here’s an example of creating a list of squares of numbers from 0 to 9 using a list comprehension:

squares = [x**2 for x in range(10)]

In this example, we use a list comprehension to generate a new list squares that contains the squares of the numbers from 0 to 9. The expression x**2 calculates the square of the current value of x, which is obtained from the range(10) iterable.

Here’s another example of creating a list of even numbers from a given list using a list comprehension:

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

In this example, we use a list comprehension to generate a new list even_numbers that contains only the even numbers from the original list numbers. The if clause filters the items in the numbers list to only include those that are divisible by 2 (i.e., even).

You can use list comprehensions with any iterable (e.g., lists, tuples, ranges) and any expression that generates a value (e.g., arithmetic expressions, string operations, function calls).

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply