List Comprehensions in Python

In this class, we discuss list comprehensions in Python.

For Complete YouTube Video: Click Here

List Comprehensions

The reader should have some prior knowledge of the list data type. Click here.

List comprehensions are one of the ways to create a list.

List comprehensions help in writing elegant and user-friendly code.

The list comprehensions consist of expressions and context.

Take example and understand expression and context in a list comprehension.

Example: [x**2 for x in range(1,7)]

From the above example, x**2, we call expression.

The remaining part for x in range(1,7) we call context.

Both expression and context are placed in a list.

The above example context is generating numbers from 1,2,3,4,5,6.

The numbers generated by the context expression are evaluated. And the result is placed in the list.

Output: [1,4,9,16,25,36]

The same output can be created using the traditional way by writing a loop and appending the value to the list.

List comprehension is easy and elegant to write the code.

Context

The context part in list comprehension consists of the arbitrary number of for and if statements.

Example: [x**2 for x in range(1,7)if x%2==0]

The comprehension mentioned above display a list [4,16,36]

For statement generate the numbers. On the generated numbers, if the condition is applied.

If the condition is true, evaluate the expression.

The list comprehension evaluates in the way mentioned above.

Example:

employees=[[“rajesh”,2000],[“suresh”,5000],[“mahesh”,7000],[“suraj”,9000]]

z=[x for x,y in employees if y > 5000]

print(z)

Output: [“Mahesh”,”suraj”]

Example with two if conditions

employees=[[“rajesh”,2000],[“suresh”,5000],[“mahesh”,7000],[“suraj”,9000]]

z=[x for x,y in employees if y > 5000 if x==’mahesh’]

print(z)

The above example will display. [“mahesh”]

If both the if conditions are true. Then the expression is evaluated.

Example with two Loops

List comprehension containing two for loops.

How will it get executed?

z=[(x,y)for x in range(3) for y in range(3) if x!=y]

print(z)

Output: [(0,1),(0,2),(1,0),(1,2),(2,0)(2,1)]

If else statement in comprehension example

z=[(x if x%2==1 else x-1) for x in range(10)]

print(z)

If condition satisfies expression evaluates. Otherwise, else will execute.

Output: [-1,1,1,3,3,5,5,7,7,9]