VOOZH about

URL: https://www.geeksforgeeks.org/python/python-list-comprehension-using-if-else/

⇱ Python List Comprehension Using If-Else - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python List Comprehension Using If-Else

Last Updated : 16 May, 2026

List comprehension with if-else is used to create lists with conditional logic concisely. It allows elements to be filtered or modified while generating the new list.

Using if-else

This method applies an if-else condition directly inside the list comprehension. Each element is checked and a corresponding value is added to the new list.


Output
['Odd', 'Even', 'Odd', 'Even', 'Odd']

Explanation:

  • Loop iterates through each number in a and n % 2 == 0 checks whether the number is even.
  • 'Even' is added for even numbers, otherwise 'Odd'.

Using Only if Condition

This method adds elements only when the condition is true. Elements that do not satisfy the condition are skipped.


Output
[2, 4]

Explanation: loop iterates through each element in a and if n % 2 == 0 filters only even numbers.

Nested if-else

Nested if-else conditions are used to handle multiple conditions inside a single list comprehension.


Output
['Other', 'Divisible by 2', 'Divisible by 3', 'Divisible by 2', 'Other']

Explanation:

  • Numbers are checked for divisibility by 2. If not divisible by 2, divisibility by 3 is checked.
  • 'Other' is added when neither condition is true.

Related Articles:

Comment
Article Tags: