SyntaxStudy
Sign Up
Python Inline If/Else in Comprehensions
Python Intermediate 3 min read

Inline If/Else in Comprehensions

Inline If/Else in Comprehensions

Use a ternary expression inside a comprehension to transform each element conditionally.

Example
nums = [1, -2, 3, -4, 5]
abs_vals = [x if x > 0 else -x for x in nums]
print(abs_vals)
# [1, 2, 3, 4, 5]
Pro Tip

Ternary inside comprehension differs from the filter if — ternary transforms, filter skips.