Search code examples
pythonlist-comprehension

List comprehension to return list if value is non-existent


I'm aiming to use list comprehension to return values in a list. Specifically, if 'x' is in a list, I want to drop all other values. However, if 'x' is not in the list, I want to return the same values (not return an empty list).

list1 = ['d','x','c']
list2 = ['d','b','c']

list1 = [s for s in list1 if s == 'x']
list2 = [s for s in list2 if s == 'x']

List2 would return []. Where I want it to be ['d','b','c']

list2 = [s for s in list2 if s == 'x' else list2]

Returns:

list2 = [s for s in list2 if s == 'x' else list2]
                                      ^^^^
SyntaxError: invalid syntax

Solution

  • This would keep all elements that aren't x

    list2 = [x for x in list2 if x != 'x']
    

    However, if x is in the list, it'll still return all other elements.

    So, you'd need two passes to check whether x does exist since list comprehension alone cannot return that information

    def filter_x(lst):
      if 'x' in lst:
        return [x for x in lst if x == 'x']
      else:
        return lst