Python List Comprehension

List comprehension is a concise way to create a list. It is commonly used in Python to create a list from an existing iterable, such as a string or a range.

List comprehension consists of an expression followed by a for clause, then zero or more for or if clauses. The result is a new list that is created by evaluating the expression in the context of the for and if clauses.

Here is an example of a list comprehension that creates a list of the squares of the numbers 0 to 9:

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

This list comprehension is equivalent to the following for loop:

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

List comprehension is a concise and efficient way to create a list, and is often used in place of a for loop. It is especially useful when you need to create a list based on a complex condition or transformation.

You can also use if clauses in list comprehension to add a condition to the expression. For example, the following list comprehension creates a list of the squares of the even numbers between 0 and 9:

even_squares = [x**2 for x in range(10) if x % 2 == 0]

This list comprehension is equivalent to the following for loop:

even_squares = []
for x in range(10):
    if x % 2 == 0:
        even_squares.append(x**2)

List comprehension is a powerful tool in Python and is used in many real-world applications.

Was this helpful?
[0]