Python Forum

Full Version: multiple condition if statement problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey everyone, i'm trying filter items out of a list, which contains specific characters.
i tried to do it like shown below, but it is not doing what i expect it to do. instread of returning the list items, which contain "a" and "c", it gives me any item which has eighter an "a" or a "c" in it.
what am i doing wrong here? or is there a better way to do it? Happy for any help!

list = ["bc", "ad", "ac", "cpd"]
new_list =[]

for x in list:
    if ("a" and "c") in x:
        new_list.append(x)
print (new_list)
Output:
['bc', 'ac', 'cpd']
First, bad idea to have a variable named the same as a keyword (list).
This works. Note the change in the if statement
test_list = ["bc", "ad", "ac", "cpd"]
new_list =[]
 
for x in test_list:
    if "a" in x and "c" in x:
        new_list.append(x)
print (new_list)
Remember that the expression "a" and "c" is a Boolean expression that actually evaluates to "c" (per the documentation), so your filter only keeps the items containing "c".

Note also that a filter can be neatly expressed as a list comprehension:

values = ["bc", "ad", "ac", "cpd"]
filtered_values = [v for v in values if "a" in v and "c" in v]
Thanks to both of you, for your help!