Why and/or operations in python statement are behaving unexpectedly?can Python 'and' return None?Replacements...

Why is quixotic not Quixotic (a proper adjective)?

How many copper coins fit inside a cubic foot?

Minimum Viable Product for RTS game?

How do I add a strong "onion flavor" to the biryani (in restaurant style)?

Found a major flaw in paper from home university – to which I would like to return

What happens if both players misunderstand the game state until it's too late?

Why is it that Bernie Sanders always called a "socialist"?

How to know if I am a 'Real Developer'

Minimum energy path of a potential energy surface

How can I differentiate duration vs starting time

Checking if an integer permutation is cyclic in Java

3D buried view in Tikz

Is layered encryption more secure than long passwords?

Now...where was I?

Why is Shelob considered evil?

Do these large-scale, human power-plant-tending robots from the Matrix movies have a name, in-universe or out?

What is the reason behind this musical reference to Pinocchio in the Close Encounters main theme?

What's the function of the word "ли" in the following contexts?

Generate PGP keys very very fast

Integral problem. Unsure of the approach.

Sets which are both Sum-free and Product-free.

bash aliases do not expand even with shopt expand_aliases

Is there a way to pause a running process on Linux systems and resume later?

Can I legally make a website about boycotting a certain company?



Why and/or operations in python statement are behaving unexpectedly?


can Python 'and' return None?Replacements for switch statement in Python?Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?“is” operator behaves unexpectedly with integersDoes Python have a ternary conditional operator?How to get the current time in PythonDoes Python have a string 'contains' substring method?













6















I have a conceptual doubt in Python. This is the code



list1=['assistant manager', 'salesperson', 'doctor', 'production manager', 'sales manager', 'schoolteacher', 'mathematics teacher']
sub1 = "teacher"
sub2 = "sales"
ans=[]

for item in list1:
if (sub1 and sub2) in item:
ans.append(item)


Here, I expect the list to be empty as none of the items satisfy the condition if sub1 and sub2 in item: But when I print the list I get the output#1 as this



>>> ans
['salesperson', 'sales manager'] # I expected an empty list here


Also, when I use or instead of and as given below



for item in list1:
if (sub1 or sub2) in item:
ans.append(item)


the output#2 I get is



>>> ans
['schoolteacher', 'mathematics teacher'] # I expected a list of words containing sub1 or sub2 as their substrings


I saw a similar looking solution here, but it does not exactly solve my problem. Both the times I get a result which I do not expect while using and and or. Can someone please explain why is this happening during both these operations?










share|improve this question

























  • (sub1 and sub2) in item what will be the result of the expression in the brackets? That will be checked against item.

    – Klaus D.
    4 hours ago













  • Change (sub1 and sub2) in item to sub1 in item and sub2 in item

    – Tom Karzes
    4 hours ago








  • 1





    Possible duplicate of can Python 'and' return None?

    – user5173426
    4 hours ago
















6















I have a conceptual doubt in Python. This is the code



list1=['assistant manager', 'salesperson', 'doctor', 'production manager', 'sales manager', 'schoolteacher', 'mathematics teacher']
sub1 = "teacher"
sub2 = "sales"
ans=[]

for item in list1:
if (sub1 and sub2) in item:
ans.append(item)


Here, I expect the list to be empty as none of the items satisfy the condition if sub1 and sub2 in item: But when I print the list I get the output#1 as this



>>> ans
['salesperson', 'sales manager'] # I expected an empty list here


Also, when I use or instead of and as given below



for item in list1:
if (sub1 or sub2) in item:
ans.append(item)


the output#2 I get is



>>> ans
['schoolteacher', 'mathematics teacher'] # I expected a list of words containing sub1 or sub2 as their substrings


I saw a similar looking solution here, but it does not exactly solve my problem. Both the times I get a result which I do not expect while using and and or. Can someone please explain why is this happening during both these operations?










share|improve this question

























  • (sub1 and sub2) in item what will be the result of the expression in the brackets? That will be checked against item.

    – Klaus D.
    4 hours ago













  • Change (sub1 and sub2) in item to sub1 in item and sub2 in item

    – Tom Karzes
    4 hours ago








  • 1





    Possible duplicate of can Python 'and' return None?

    – user5173426
    4 hours ago














6












6








6








I have a conceptual doubt in Python. This is the code



list1=['assistant manager', 'salesperson', 'doctor', 'production manager', 'sales manager', 'schoolteacher', 'mathematics teacher']
sub1 = "teacher"
sub2 = "sales"
ans=[]

for item in list1:
if (sub1 and sub2) in item:
ans.append(item)


Here, I expect the list to be empty as none of the items satisfy the condition if sub1 and sub2 in item: But when I print the list I get the output#1 as this



>>> ans
['salesperson', 'sales manager'] # I expected an empty list here


Also, when I use or instead of and as given below



for item in list1:
if (sub1 or sub2) in item:
ans.append(item)


the output#2 I get is



>>> ans
['schoolteacher', 'mathematics teacher'] # I expected a list of words containing sub1 or sub2 as their substrings


I saw a similar looking solution here, but it does not exactly solve my problem. Both the times I get a result which I do not expect while using and and or. Can someone please explain why is this happening during both these operations?










share|improve this question
















I have a conceptual doubt in Python. This is the code



list1=['assistant manager', 'salesperson', 'doctor', 'production manager', 'sales manager', 'schoolteacher', 'mathematics teacher']
sub1 = "teacher"
sub2 = "sales"
ans=[]

for item in list1:
if (sub1 and sub2) in item:
ans.append(item)


Here, I expect the list to be empty as none of the items satisfy the condition if sub1 and sub2 in item: But when I print the list I get the output#1 as this



>>> ans
['salesperson', 'sales manager'] # I expected an empty list here


Also, when I use or instead of and as given below



for item in list1:
if (sub1 or sub2) in item:
ans.append(item)


the output#2 I get is



>>> ans
['schoolteacher', 'mathematics teacher'] # I expected a list of words containing sub1 or sub2 as their substrings


I saw a similar looking solution here, but it does not exactly solve my problem. Both the times I get a result which I do not expect while using and and or. Can someone please explain why is this happening during both these operations?







python logical-operators






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 4 hours ago







satya

















asked 4 hours ago









satyasatya

13811




13811













  • (sub1 and sub2) in item what will be the result of the expression in the brackets? That will be checked against item.

    – Klaus D.
    4 hours ago













  • Change (sub1 and sub2) in item to sub1 in item and sub2 in item

    – Tom Karzes
    4 hours ago








  • 1





    Possible duplicate of can Python 'and' return None?

    – user5173426
    4 hours ago



















  • (sub1 and sub2) in item what will be the result of the expression in the brackets? That will be checked against item.

    – Klaus D.
    4 hours ago













  • Change (sub1 and sub2) in item to sub1 in item and sub2 in item

    – Tom Karzes
    4 hours ago








  • 1





    Possible duplicate of can Python 'and' return None?

    – user5173426
    4 hours ago

















(sub1 and sub2) in item what will be the result of the expression in the brackets? That will be checked against item.

– Klaus D.
4 hours ago







(sub1 and sub2) in item what will be the result of the expression in the brackets? That will be checked against item.

– Klaus D.
4 hours ago















Change (sub1 and sub2) in item to sub1 in item and sub2 in item

– Tom Karzes
4 hours ago







Change (sub1 and sub2) in item to sub1 in item and sub2 in item

– Tom Karzes
4 hours ago






1




1





Possible duplicate of can Python 'and' return None?

– user5173426
4 hours ago





Possible duplicate of can Python 'and' return None?

– user5173426
4 hours ago












2 Answers
2






active

oldest

votes


















7














("teacher" and "sales") in "salesmanager" do not mean the same in Python and in English.



In English, it is synonynous to ("teacher" in "salesmanager") and ("sales" in "salesmanager") (which Python would understand as you thought it should, and evaluate to False).



Python on the other hand will first evaluate "teacher" and "sales", because it is in parentheses, and thus has higher priority. and will return the first argument if falsy, otherwise the second argument. "teacher" is not falsy, so "teacher" and "sales" evaluates as "sales". Then, Python continues to evaluate "sales" in "salesmanager", and returns True.






share|improve this answer































    4














    The and and or operators don't do what you think they do. Try breaking up your expressions:



    if sub1 in item or sub2 in item:

    if sub1 in item and sub2 in item:


    The and operator evaluates its left-hand operand and, if the result is truthy, returns the right-hand operand, otherwise the left-hand operand.



    The or operator evaluates its left-hand operand and, if the result is falsy, returns the right-hand operand, otherwise the left-hand operand.



    So, in your first expression evaluates as follows:



    (sub1 and sub2) in item
    ("teacher" and "sales") in item
    ("sales") in item


    which is not what you expected.



    Similarly for your second expression:



    (sub1 or sub2) in item
    ("teacher" or "sales") in item
    ("teacher") in item





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54821841%2fwhy-and-or-operations-in-python-statement-are-behaving-unexpectedly%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      7














      ("teacher" and "sales") in "salesmanager" do not mean the same in Python and in English.



      In English, it is synonynous to ("teacher" in "salesmanager") and ("sales" in "salesmanager") (which Python would understand as you thought it should, and evaluate to False).



      Python on the other hand will first evaluate "teacher" and "sales", because it is in parentheses, and thus has higher priority. and will return the first argument if falsy, otherwise the second argument. "teacher" is not falsy, so "teacher" and "sales" evaluates as "sales". Then, Python continues to evaluate "sales" in "salesmanager", and returns True.






      share|improve this answer




























        7














        ("teacher" and "sales") in "salesmanager" do not mean the same in Python and in English.



        In English, it is synonynous to ("teacher" in "salesmanager") and ("sales" in "salesmanager") (which Python would understand as you thought it should, and evaluate to False).



        Python on the other hand will first evaluate "teacher" and "sales", because it is in parentheses, and thus has higher priority. and will return the first argument if falsy, otherwise the second argument. "teacher" is not falsy, so "teacher" and "sales" evaluates as "sales". Then, Python continues to evaluate "sales" in "salesmanager", and returns True.






        share|improve this answer


























          7












          7








          7







          ("teacher" and "sales") in "salesmanager" do not mean the same in Python and in English.



          In English, it is synonynous to ("teacher" in "salesmanager") and ("sales" in "salesmanager") (which Python would understand as you thought it should, and evaluate to False).



          Python on the other hand will first evaluate "teacher" and "sales", because it is in parentheses, and thus has higher priority. and will return the first argument if falsy, otherwise the second argument. "teacher" is not falsy, so "teacher" and "sales" evaluates as "sales". Then, Python continues to evaluate "sales" in "salesmanager", and returns True.






          share|improve this answer













          ("teacher" and "sales") in "salesmanager" do not mean the same in Python and in English.



          In English, it is synonynous to ("teacher" in "salesmanager") and ("sales" in "salesmanager") (which Python would understand as you thought it should, and evaluate to False).



          Python on the other hand will first evaluate "teacher" and "sales", because it is in parentheses, and thus has higher priority. and will return the first argument if falsy, otherwise the second argument. "teacher" is not falsy, so "teacher" and "sales" evaluates as "sales". Then, Python continues to evaluate "sales" in "salesmanager", and returns True.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 4 hours ago









          AmadanAmadan

          131k13143195




          131k13143195

























              4














              The and and or operators don't do what you think they do. Try breaking up your expressions:



              if sub1 in item or sub2 in item:

              if sub1 in item and sub2 in item:


              The and operator evaluates its left-hand operand and, if the result is truthy, returns the right-hand operand, otherwise the left-hand operand.



              The or operator evaluates its left-hand operand and, if the result is falsy, returns the right-hand operand, otherwise the left-hand operand.



              So, in your first expression evaluates as follows:



              (sub1 and sub2) in item
              ("teacher" and "sales") in item
              ("sales") in item


              which is not what you expected.



              Similarly for your second expression:



              (sub1 or sub2) in item
              ("teacher" or "sales") in item
              ("teacher") in item





              share|improve this answer




























                4














                The and and or operators don't do what you think they do. Try breaking up your expressions:



                if sub1 in item or sub2 in item:

                if sub1 in item and sub2 in item:


                The and operator evaluates its left-hand operand and, if the result is truthy, returns the right-hand operand, otherwise the left-hand operand.



                The or operator evaluates its left-hand operand and, if the result is falsy, returns the right-hand operand, otherwise the left-hand operand.



                So, in your first expression evaluates as follows:



                (sub1 and sub2) in item
                ("teacher" and "sales") in item
                ("sales") in item


                which is not what you expected.



                Similarly for your second expression:



                (sub1 or sub2) in item
                ("teacher" or "sales") in item
                ("teacher") in item





                share|improve this answer


























                  4












                  4








                  4







                  The and and or operators don't do what you think they do. Try breaking up your expressions:



                  if sub1 in item or sub2 in item:

                  if sub1 in item and sub2 in item:


                  The and operator evaluates its left-hand operand and, if the result is truthy, returns the right-hand operand, otherwise the left-hand operand.



                  The or operator evaluates its left-hand operand and, if the result is falsy, returns the right-hand operand, otherwise the left-hand operand.



                  So, in your first expression evaluates as follows:



                  (sub1 and sub2) in item
                  ("teacher" and "sales") in item
                  ("sales") in item


                  which is not what you expected.



                  Similarly for your second expression:



                  (sub1 or sub2) in item
                  ("teacher" or "sales") in item
                  ("teacher") in item





                  share|improve this answer













                  The and and or operators don't do what you think they do. Try breaking up your expressions:



                  if sub1 in item or sub2 in item:

                  if sub1 in item and sub2 in item:


                  The and operator evaluates its left-hand operand and, if the result is truthy, returns the right-hand operand, otherwise the left-hand operand.



                  The or operator evaluates its left-hand operand and, if the result is falsy, returns the right-hand operand, otherwise the left-hand operand.



                  So, in your first expression evaluates as follows:



                  (sub1 and sub2) in item
                  ("teacher" and "sales") in item
                  ("sales") in item


                  which is not what you expected.



                  Similarly for your second expression:



                  (sub1 or sub2) in item
                  ("teacher" or "sales") in item
                  ("teacher") in item






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 4 hours ago









                  RobᵩRobᵩ

                  116k13138222




                  116k13138222






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54821841%2fwhy-and-or-operations-in-python-statement-are-behaving-unexpectedly%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Szabolcs (Ungheria) Altri progetti | Menu di navigazione48°10′14.56″N 21°29′33.14″E /...

                      Discografia di Klaus Schulze Indice Album in studio | Album dal vivo | Singoli | Antologie | Colonne...

                      How to make inet_server_addr() return localhost in spite of ::1/128RETURN NEXT in Postgres FunctionConnect to...