Python Forum
multiple condition if statement problem
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
multiple condition if statement problem
#1
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']
Reply
#2
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)
tester_V and FelixReiter like this post
Reply
#3
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]
FelixReiter and tester_V like this post
Reply
#4
Thanks to both of you, for your help!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to write the condition for deleting multiple lines? Lky 3 1,129 Jul-10-2022, 02:28 PM
Last Post: Lky
  problem with while statement. BobSmoss 3 1,655 Jan-08-2022, 03:22 PM
Last Post: BobSmoss
  How do you format Update statement with multiple conditions hammer 4 2,093 Dec-16-2021, 10:49 PM
Last Post: hammer
  How to map two data frames based on multiple condition SriRajesh 0 1,472 Oct-27-2021, 02:43 PM
Last Post: SriRajesh
  Problem in if-else statement shantanu97 2 2,421 Apr-09-2021, 06:37 AM
Last Post: shantanu97
  Problem with If statement and dataframe Milfredo 1 1,765 Sep-16-2020, 05:50 AM
Last Post: Milfredo
  Problem with If else statement Milfredo 5 2,579 Aug-30-2020, 06:32 PM
Last Post: Milfredo
  Problem with a 'break' statement. christopher3786 3 2,429 Jun-20-2020, 10:16 AM
Last Post: pyzyx3qwerty
  else condition not called when if condition is false Sandz1286 10 5,844 Jun-05-2020, 05:01 PM
Last Post: ebolisa
  Python Hangman Game - Multiple Letters Problem t0rn 4 4,634 Jun-05-2020, 11:27 AM
Last Post: t0rn

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020