Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading