Python Forum
multiple condition if statement problem - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: multiple condition if statement problem (/thread-31931.html)



multiple condition if statement problem - FelixReiter - Jan-10-2021

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']



RE: multiple condition if statement problem - jefsummers - Jan-10-2021

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)



RE: multiple condition if statement problem - ndc85430 - Jan-10-2021

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]



RE: multiple condition if statement problem - FelixReiter - Jan-11-2021

Thanks to both of you, for your help!