Search code examples
pythonlist-comprehension

Python list comprehension for double if condition


I need to clarify the list comprehension for double if statement.

a = ["apple", "banana", "cherry", "kiwi", 'mango']
c = []

# Conventional method
for b in a:
  if 'a' in b:
     if b != 'apple':
      c.append(b)
print(c)

The return outcomes are:

['banana', 'mango']

How could I rephrase the Python list comprehension method?


Solution

  • You can either combine the codition in a single expression in list comprehension:

    a = ["apple", "banana", "cherry", "kiwi", 'mango']
    
    c = [x for x in a if 'a' in x and x != 'apple']
    
    print(c) # ['banana', 'mango']
    

    or composite multiple list comprehension with conditional element selection:

    a = ["apple", "banana", "cherry", "kiwi", 'mango']
    
    c = [x for x in [y for y in a if 'a' in y] if x != 'apple']
    
    print(c) # ['banana', 'mango']