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)
FelixReiter and tester_V 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
  Problem in if-else statement shantanu97 2 446 Apr-09-2021, 06:37 AM
Last Post: shantanu97
  Problem with If statement and dataframe Milfredo 1 463 Sep-16-2020, 05:50 AM
Last Post: Milfredo
  Problem with If else statement Milfredo 5 627 Aug-30-2020, 06:32 PM
Last Post: Milfredo
  Problem with a 'break' statement. christopher3786 3 648 Jun-20-2020, 10:16 AM
Last Post: pyzyx3qwerty
  else condition not called when if condition is false Sandz1286 10 2,024 Jun-05-2020, 05:01 PM
Last Post: ebolisa
  Python Hangman Game - Multiple Letters Problem t0rn 4 1,180 Jun-05-2020, 11:27 AM
Last Post: t0rn
  [HELP] Nested conditional? double condition followed by another condition. penahuse 25 2,203 Jun-01-2020, 06:00 PM
Last Post: penahuse
  using element on a list as condition statement glennford49 11 1,513 May-21-2020, 12:53 PM
Last Post: hussainmujtaba
  SyntaxError: multiple statements found while compiling a single statement Kayode_Odeyinka 1 918 Mar-12-2020, 05:50 PM
Last Post: micseydel
  Problem with an IF statement Ryan_Todd 13 1,608 Jan-30-2020, 08:22 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

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