DEV Community

Cover image for List Comprehension in Python
Karthick (k)
Karthick (k)

Posted on

List Comprehension in Python

List comprehension is a concise way to create new lists by applying an expression to each item in an existing iterable like a list, tuple or range. It helps to write clean, readable and efficient code compared to traditional loops.

Suppose you want to square every number in a list:

a = [2, 3, 4, 5]
res = [val ** 2 for val in a]
print(res)
Enter fullscreen mode Exit fullscreen mode

Output

[4, 9, 16, 25]

Explanation: res = [val ** 2 for val in a] use **list comprehension **to create a new list by squaring each number in a.

Syntax

[expression for item in iterable if condition]

Enter fullscreen mode Exit fullscreen mode

Parameters:

  1. expression: operation or value to include in the new list.
  2. item: current element from the iterable.
  3. iterable: sequence like a list, tuple or range.
  4. if condition (optional): filter to include only items that satisfy the condition.

Conditional Statements in List Comprehension

List comprehensions can use conditions to select or transform items based on specific rules. This allows creating customised lists more concisely and improves code readability and efficiency.

Example 1: This code uses a list comprehension with a condition to create a new list with only even numbers from list a.

a = [1, 2, 3, 4, 5]
res = [val for val in a if val % 2 == 0]
print(res)
Enter fullscreen mode Exit fullscreen mode

Output

[2, 4]

Example 2: Here, list comprehension is used with a condition to create a new list with numbers greater than 10 from list b.

b = [5, 12, 7, 18, 3, 20]
res = [val for val in b if val > 10]
print(res)
Enter fullscreen mode Exit fullscreen mode

Output

[12, 18, 20]

For Loop vs List Comprehension

For Loop

  1. Uses multiple lines of code
  2. Requires manual appending of elements
  3. Better for complex logic and conditions
  4. More readable for long operations

List Comprehension

  1. Uses a single line of code.
  2. Creates the list directly.
  3. Better for simple and concise operations
  4. More compact and faster to write

Top comments (0)