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

Python – filtering list of strings based on multiple conditions

I’m looking to filter a list of strings based on multiple conditions. Adding the output to a new list.

list1 = ['Bike', 'Street Bike', 'Custom Bike', 'Custom Street Bike', 'City Bike', 
'Cruiser Street Bike']

list2 = []

For the purposes of this example, I would like to extract the list items containing ‘Street’ & ‘Bike’

I’ve tried the following method but it is returning all items on the list

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 list1 if 'Street' and 'Bike' in s]

Expected output

   print(list2)  
   ['Street Bike', 'Custom Street Bike', 'Cruiser Street Bike']

>Solution :

The expression if 'Street' and 'Bike' in s evaluates to True all the time because what it is saying is: if 'Street', which is always True because 'Street' is Truthy. and 'Bike' in s which is also always True because ‘Bike’ is in all items in the list. So you need

if 'Street' in s and 'Bike' in s:
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