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
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: