Python Ternary Operator Without else





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







55















Is it possible to do this on one line in Python?



if <condition>:
myList.append('myString')


I have tried the ternary operator:



myList.append('myString' if <condition>)


but my IDE (MyEclipse) didn't like it, without an else.










share|improve this question































    55















    Is it possible to do this on one line in Python?



    if <condition>:
    myList.append('myString')


    I have tried the ternary operator:



    myList.append('myString' if <condition>)


    but my IDE (MyEclipse) didn't like it, without an else.










    share|improve this question



























      55












      55








      55


      12






      Is it possible to do this on one line in Python?



      if <condition>:
      myList.append('myString')


      I have tried the ternary operator:



      myList.append('myString' if <condition>)


      but my IDE (MyEclipse) didn't like it, without an else.










      share|improve this question
















      Is it possible to do this on one line in Python?



      if <condition>:
      myList.append('myString')


      I have tried the ternary operator:



      myList.append('myString' if <condition>)


      but my IDE (MyEclipse) didn't like it, without an else.







      python ternary






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jul 9 '18 at 8:22









      Filipp W.

      2,08511130




      2,08511130










      asked Aug 30 '12 at 14:56









      JCBJCB

      5174820




      5174820
























          6 Answers
          6






          active

          oldest

          votes


















          78














          Yes, you can do this:



          <condition> and myList.append('myString')


          If <condition> is false, then short-circuiting will kick in and the right-hand side won't be evaluated. If <condition> is true, then the right-hand side will be evaluated and the element will be appended.



          I'll just point out that doing the above is quite non-pythonic, and it would probably be best to write this, regardless:



          if <condition>: myList.append('myString')


          Demonstration:



          >>> myList = 
          >>> False and myList.append('myString')
          False
          >>> myList

          >>> True and myList.append('myString')
          >>> myList
          ['myString']





          share|improve this answer





















          • 3





            While this answer is technically correct, it's not a good programming practice. Since Python aims to be a language that's easily readable, this code would be considered non-Pythonic.

            – L S
            Oct 15 '13 at 9:44






          • 4





            @LS: I agree, that's why I said it would probably be best to just use an if statement. But I modified the answer a bit to make that clearer.

            – Claudiu
            Oct 15 '13 at 15:54








          • 1





            fyi the second example will fail pep8 checks: E701 multiple statements on one line so also non-pythonic... ;)

            – Cas
            Feb 18 '17 at 17:59











          • Note that this and-shortcircuiting doesn't seem to work for assignments: <condition> and (strng = 'myString')

            – oulenz
            Mar 24 '18 at 10:45











          • This is not foolproof if you have objects/dictionaries in the condition: x = object['attribute'] or None will throw a KeyError exception if there is no attribute key in object. The correct way will still be: x = object['attribute'] if 'attribute' in object else None

            – barry_allen
            Sep 4 '18 at 8:10





















          29














          The reason the language doesn't allow you to use the syntax



          variable = "something" if a_condition


          without else is that, in the case where a_condition == False, variable is suddenly unknown. Maybe it could default to None, but Python requires that all variable assignments actually result in explicit assignments. This also applies to cases such as your function call, as the value passed to the function is evaluated just as the RHS of an assignment statement would be.



          Similarly, all returns must actually return, even if they are conditional returns. Eg:



          return variable if a_condition


          is not allowed, but



          return variable if a_condition else None


          is allowed, since the second example is guaranteed to explicitly return something.






          share|improve this answer





















          • 1





            It's ironic how Python doesn't allow us to use this so that variable is never none yet variable=None is perfectly legal. :D

            – Guy
            Feb 15 '14 at 15:51






          • 1





            But I wanted to use it like this: continue if i == 0 in a for loop.

            – karantan
            Sep 29 '15 at 12:53






          • 1





            Are you allowed to do else pass?

            – OldBunny2800
            Jan 11 '17 at 0:51






          • 4





            else pass doesn't work because the ternary expression should return a value that can be passed to return. pass is not a valid return value.

            – Emmett Butler
            Feb 9 '17 at 23:25






          • 1





            I don't agree that this motivation is the real reason, given that if a_condition: variable = "something" and if a_condition: return variable are legal. So it is essentially an arbitrary syntactic choice of python.

            – oulenz
            Mar 24 '18 at 10:40



















          12














          if <condition>: myList.append('myString')


          Otherwise, no. Why the need to put it on one line?



          Note that the "ternary operator" is an operator. Like any operator, it must return something, so how can you have a ternary operator without the else clause? What is it supposed to return if the condition isn't true-like?






          share|improve this answer































            5














            You are basically asking for do_thing() if <condition> else pass construct (which will throw SyntaxError, if ran). As I have discovered during research for (somewhat) similar question do_thing() if condition else None is as close as you can get (which is just another way to do <condition> and do_thing()). So, to summarize this idea and other answers, here are your options:





            • if <condition>: myList.append('myString') — seems to be the least 'hacky' (and thus preferred) way

            • <condition> and myList.append('myString')

            • myList.append('myString') if <condition> else None






            share|improve this answer































              3














              myList.extend(['myString'] if condition else ) would also work, though it's more work than the other solutions.






              share|improve this answer































                0














                You can do something like this:



                myList.append('myString') if <condition> else False


                or



                myList.append('myString') if <condition> else 0





                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%2f12199757%2fpython-ternary-operator-without-else%23new-answer', 'question_page');
                  }
                  );

                  Post as a guest















                  Required, but never shown

























                  6 Answers
                  6






                  active

                  oldest

                  votes








                  6 Answers
                  6






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  78














                  Yes, you can do this:



                  <condition> and myList.append('myString')


                  If <condition> is false, then short-circuiting will kick in and the right-hand side won't be evaluated. If <condition> is true, then the right-hand side will be evaluated and the element will be appended.



                  I'll just point out that doing the above is quite non-pythonic, and it would probably be best to write this, regardless:



                  if <condition>: myList.append('myString')


                  Demonstration:



                  >>> myList = 
                  >>> False and myList.append('myString')
                  False
                  >>> myList

                  >>> True and myList.append('myString')
                  >>> myList
                  ['myString']





                  share|improve this answer





















                  • 3





                    While this answer is technically correct, it's not a good programming practice. Since Python aims to be a language that's easily readable, this code would be considered non-Pythonic.

                    – L S
                    Oct 15 '13 at 9:44






                  • 4





                    @LS: I agree, that's why I said it would probably be best to just use an if statement. But I modified the answer a bit to make that clearer.

                    – Claudiu
                    Oct 15 '13 at 15:54








                  • 1





                    fyi the second example will fail pep8 checks: E701 multiple statements on one line so also non-pythonic... ;)

                    – Cas
                    Feb 18 '17 at 17:59











                  • Note that this and-shortcircuiting doesn't seem to work for assignments: <condition> and (strng = 'myString')

                    – oulenz
                    Mar 24 '18 at 10:45











                  • This is not foolproof if you have objects/dictionaries in the condition: x = object['attribute'] or None will throw a KeyError exception if there is no attribute key in object. The correct way will still be: x = object['attribute'] if 'attribute' in object else None

                    – barry_allen
                    Sep 4 '18 at 8:10


















                  78














                  Yes, you can do this:



                  <condition> and myList.append('myString')


                  If <condition> is false, then short-circuiting will kick in and the right-hand side won't be evaluated. If <condition> is true, then the right-hand side will be evaluated and the element will be appended.



                  I'll just point out that doing the above is quite non-pythonic, and it would probably be best to write this, regardless:



                  if <condition>: myList.append('myString')


                  Demonstration:



                  >>> myList = 
                  >>> False and myList.append('myString')
                  False
                  >>> myList

                  >>> True and myList.append('myString')
                  >>> myList
                  ['myString']





                  share|improve this answer





















                  • 3





                    While this answer is technically correct, it's not a good programming practice. Since Python aims to be a language that's easily readable, this code would be considered non-Pythonic.

                    – L S
                    Oct 15 '13 at 9:44






                  • 4





                    @LS: I agree, that's why I said it would probably be best to just use an if statement. But I modified the answer a bit to make that clearer.

                    – Claudiu
                    Oct 15 '13 at 15:54








                  • 1





                    fyi the second example will fail pep8 checks: E701 multiple statements on one line so also non-pythonic... ;)

                    – Cas
                    Feb 18 '17 at 17:59











                  • Note that this and-shortcircuiting doesn't seem to work for assignments: <condition> and (strng = 'myString')

                    – oulenz
                    Mar 24 '18 at 10:45











                  • This is not foolproof if you have objects/dictionaries in the condition: x = object['attribute'] or None will throw a KeyError exception if there is no attribute key in object. The correct way will still be: x = object['attribute'] if 'attribute' in object else None

                    – barry_allen
                    Sep 4 '18 at 8:10
















                  78












                  78








                  78







                  Yes, you can do this:



                  <condition> and myList.append('myString')


                  If <condition> is false, then short-circuiting will kick in and the right-hand side won't be evaluated. If <condition> is true, then the right-hand side will be evaluated and the element will be appended.



                  I'll just point out that doing the above is quite non-pythonic, and it would probably be best to write this, regardless:



                  if <condition>: myList.append('myString')


                  Demonstration:



                  >>> myList = 
                  >>> False and myList.append('myString')
                  False
                  >>> myList

                  >>> True and myList.append('myString')
                  >>> myList
                  ['myString']





                  share|improve this answer















                  Yes, you can do this:



                  <condition> and myList.append('myString')


                  If <condition> is false, then short-circuiting will kick in and the right-hand side won't be evaluated. If <condition> is true, then the right-hand side will be evaluated and the element will be appended.



                  I'll just point out that doing the above is quite non-pythonic, and it would probably be best to write this, regardless:



                  if <condition>: myList.append('myString')


                  Demonstration:



                  >>> myList = 
                  >>> False and myList.append('myString')
                  False
                  >>> myList

                  >>> True and myList.append('myString')
                  >>> myList
                  ['myString']






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Oct 15 '13 at 15:54

























                  answered Aug 30 '12 at 15:05









                  ClaudiuClaudiu

                  129k127399594




                  129k127399594








                  • 3





                    While this answer is technically correct, it's not a good programming practice. Since Python aims to be a language that's easily readable, this code would be considered non-Pythonic.

                    – L S
                    Oct 15 '13 at 9:44






                  • 4





                    @LS: I agree, that's why I said it would probably be best to just use an if statement. But I modified the answer a bit to make that clearer.

                    – Claudiu
                    Oct 15 '13 at 15:54








                  • 1





                    fyi the second example will fail pep8 checks: E701 multiple statements on one line so also non-pythonic... ;)

                    – Cas
                    Feb 18 '17 at 17:59











                  • Note that this and-shortcircuiting doesn't seem to work for assignments: <condition> and (strng = 'myString')

                    – oulenz
                    Mar 24 '18 at 10:45











                  • This is not foolproof if you have objects/dictionaries in the condition: x = object['attribute'] or None will throw a KeyError exception if there is no attribute key in object. The correct way will still be: x = object['attribute'] if 'attribute' in object else None

                    – barry_allen
                    Sep 4 '18 at 8:10
















                  • 3





                    While this answer is technically correct, it's not a good programming practice. Since Python aims to be a language that's easily readable, this code would be considered non-Pythonic.

                    – L S
                    Oct 15 '13 at 9:44






                  • 4





                    @LS: I agree, that's why I said it would probably be best to just use an if statement. But I modified the answer a bit to make that clearer.

                    – Claudiu
                    Oct 15 '13 at 15:54








                  • 1





                    fyi the second example will fail pep8 checks: E701 multiple statements on one line so also non-pythonic... ;)

                    – Cas
                    Feb 18 '17 at 17:59











                  • Note that this and-shortcircuiting doesn't seem to work for assignments: <condition> and (strng = 'myString')

                    – oulenz
                    Mar 24 '18 at 10:45











                  • This is not foolproof if you have objects/dictionaries in the condition: x = object['attribute'] or None will throw a KeyError exception if there is no attribute key in object. The correct way will still be: x = object['attribute'] if 'attribute' in object else None

                    – barry_allen
                    Sep 4 '18 at 8:10










                  3




                  3





                  While this answer is technically correct, it's not a good programming practice. Since Python aims to be a language that's easily readable, this code would be considered non-Pythonic.

                  – L S
                  Oct 15 '13 at 9:44





                  While this answer is technically correct, it's not a good programming practice. Since Python aims to be a language that's easily readable, this code would be considered non-Pythonic.

                  – L S
                  Oct 15 '13 at 9:44




                  4




                  4





                  @LS: I agree, that's why I said it would probably be best to just use an if statement. But I modified the answer a bit to make that clearer.

                  – Claudiu
                  Oct 15 '13 at 15:54







                  @LS: I agree, that's why I said it would probably be best to just use an if statement. But I modified the answer a bit to make that clearer.

                  – Claudiu
                  Oct 15 '13 at 15:54






                  1




                  1





                  fyi the second example will fail pep8 checks: E701 multiple statements on one line so also non-pythonic... ;)

                  – Cas
                  Feb 18 '17 at 17:59





                  fyi the second example will fail pep8 checks: E701 multiple statements on one line so also non-pythonic... ;)

                  – Cas
                  Feb 18 '17 at 17:59













                  Note that this and-shortcircuiting doesn't seem to work for assignments: <condition> and (strng = 'myString')

                  – oulenz
                  Mar 24 '18 at 10:45





                  Note that this and-shortcircuiting doesn't seem to work for assignments: <condition> and (strng = 'myString')

                  – oulenz
                  Mar 24 '18 at 10:45













                  This is not foolproof if you have objects/dictionaries in the condition: x = object['attribute'] or None will throw a KeyError exception if there is no attribute key in object. The correct way will still be: x = object['attribute'] if 'attribute' in object else None

                  – barry_allen
                  Sep 4 '18 at 8:10







                  This is not foolproof if you have objects/dictionaries in the condition: x = object['attribute'] or None will throw a KeyError exception if there is no attribute key in object. The correct way will still be: x = object['attribute'] if 'attribute' in object else None

                  – barry_allen
                  Sep 4 '18 at 8:10















                  29














                  The reason the language doesn't allow you to use the syntax



                  variable = "something" if a_condition


                  without else is that, in the case where a_condition == False, variable is suddenly unknown. Maybe it could default to None, but Python requires that all variable assignments actually result in explicit assignments. This also applies to cases such as your function call, as the value passed to the function is evaluated just as the RHS of an assignment statement would be.



                  Similarly, all returns must actually return, even if they are conditional returns. Eg:



                  return variable if a_condition


                  is not allowed, but



                  return variable if a_condition else None


                  is allowed, since the second example is guaranteed to explicitly return something.






                  share|improve this answer





















                  • 1





                    It's ironic how Python doesn't allow us to use this so that variable is never none yet variable=None is perfectly legal. :D

                    – Guy
                    Feb 15 '14 at 15:51






                  • 1





                    But I wanted to use it like this: continue if i == 0 in a for loop.

                    – karantan
                    Sep 29 '15 at 12:53






                  • 1





                    Are you allowed to do else pass?

                    – OldBunny2800
                    Jan 11 '17 at 0:51






                  • 4





                    else pass doesn't work because the ternary expression should return a value that can be passed to return. pass is not a valid return value.

                    – Emmett Butler
                    Feb 9 '17 at 23:25






                  • 1





                    I don't agree that this motivation is the real reason, given that if a_condition: variable = "something" and if a_condition: return variable are legal. So it is essentially an arbitrary syntactic choice of python.

                    – oulenz
                    Mar 24 '18 at 10:40
















                  29














                  The reason the language doesn't allow you to use the syntax



                  variable = "something" if a_condition


                  without else is that, in the case where a_condition == False, variable is suddenly unknown. Maybe it could default to None, but Python requires that all variable assignments actually result in explicit assignments. This also applies to cases such as your function call, as the value passed to the function is evaluated just as the RHS of an assignment statement would be.



                  Similarly, all returns must actually return, even if they are conditional returns. Eg:



                  return variable if a_condition


                  is not allowed, but



                  return variable if a_condition else None


                  is allowed, since the second example is guaranteed to explicitly return something.






                  share|improve this answer





















                  • 1





                    It's ironic how Python doesn't allow us to use this so that variable is never none yet variable=None is perfectly legal. :D

                    – Guy
                    Feb 15 '14 at 15:51






                  • 1





                    But I wanted to use it like this: continue if i == 0 in a for loop.

                    – karantan
                    Sep 29 '15 at 12:53






                  • 1





                    Are you allowed to do else pass?

                    – OldBunny2800
                    Jan 11 '17 at 0:51






                  • 4





                    else pass doesn't work because the ternary expression should return a value that can be passed to return. pass is not a valid return value.

                    – Emmett Butler
                    Feb 9 '17 at 23:25






                  • 1





                    I don't agree that this motivation is the real reason, given that if a_condition: variable = "something" and if a_condition: return variable are legal. So it is essentially an arbitrary syntactic choice of python.

                    – oulenz
                    Mar 24 '18 at 10:40














                  29












                  29








                  29







                  The reason the language doesn't allow you to use the syntax



                  variable = "something" if a_condition


                  without else is that, in the case where a_condition == False, variable is suddenly unknown. Maybe it could default to None, but Python requires that all variable assignments actually result in explicit assignments. This also applies to cases such as your function call, as the value passed to the function is evaluated just as the RHS of an assignment statement would be.



                  Similarly, all returns must actually return, even if they are conditional returns. Eg:



                  return variable if a_condition


                  is not allowed, but



                  return variable if a_condition else None


                  is allowed, since the second example is guaranteed to explicitly return something.






                  share|improve this answer















                  The reason the language doesn't allow you to use the syntax



                  variable = "something" if a_condition


                  without else is that, in the case where a_condition == False, variable is suddenly unknown. Maybe it could default to None, but Python requires that all variable assignments actually result in explicit assignments. This also applies to cases such as your function call, as the value passed to the function is evaluated just as the RHS of an assignment statement would be.



                  Similarly, all returns must actually return, even if they are conditional returns. Eg:



                  return variable if a_condition


                  is not allowed, but



                  return variable if a_condition else None


                  is allowed, since the second example is guaranteed to explicitly return something.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jul 9 '18 at 10:08









                  Filipp W.

                  2,08511130




                  2,08511130










                  answered Aug 30 '12 at 14:59









                  Emmett ButlerEmmett Butler

                  3,64422034




                  3,64422034








                  • 1





                    It's ironic how Python doesn't allow us to use this so that variable is never none yet variable=None is perfectly legal. :D

                    – Guy
                    Feb 15 '14 at 15:51






                  • 1





                    But I wanted to use it like this: continue if i == 0 in a for loop.

                    – karantan
                    Sep 29 '15 at 12:53






                  • 1





                    Are you allowed to do else pass?

                    – OldBunny2800
                    Jan 11 '17 at 0:51






                  • 4





                    else pass doesn't work because the ternary expression should return a value that can be passed to return. pass is not a valid return value.

                    – Emmett Butler
                    Feb 9 '17 at 23:25






                  • 1





                    I don't agree that this motivation is the real reason, given that if a_condition: variable = "something" and if a_condition: return variable are legal. So it is essentially an arbitrary syntactic choice of python.

                    – oulenz
                    Mar 24 '18 at 10:40














                  • 1





                    It's ironic how Python doesn't allow us to use this so that variable is never none yet variable=None is perfectly legal. :D

                    – Guy
                    Feb 15 '14 at 15:51






                  • 1





                    But I wanted to use it like this: continue if i == 0 in a for loop.

                    – karantan
                    Sep 29 '15 at 12:53






                  • 1





                    Are you allowed to do else pass?

                    – OldBunny2800
                    Jan 11 '17 at 0:51






                  • 4





                    else pass doesn't work because the ternary expression should return a value that can be passed to return. pass is not a valid return value.

                    – Emmett Butler
                    Feb 9 '17 at 23:25






                  • 1





                    I don't agree that this motivation is the real reason, given that if a_condition: variable = "something" and if a_condition: return variable are legal. So it is essentially an arbitrary syntactic choice of python.

                    – oulenz
                    Mar 24 '18 at 10:40








                  1




                  1





                  It's ironic how Python doesn't allow us to use this so that variable is never none yet variable=None is perfectly legal. :D

                  – Guy
                  Feb 15 '14 at 15:51





                  It's ironic how Python doesn't allow us to use this so that variable is never none yet variable=None is perfectly legal. :D

                  – Guy
                  Feb 15 '14 at 15:51




                  1




                  1





                  But I wanted to use it like this: continue if i == 0 in a for loop.

                  – karantan
                  Sep 29 '15 at 12:53





                  But I wanted to use it like this: continue if i == 0 in a for loop.

                  – karantan
                  Sep 29 '15 at 12:53




                  1




                  1





                  Are you allowed to do else pass?

                  – OldBunny2800
                  Jan 11 '17 at 0:51





                  Are you allowed to do else pass?

                  – OldBunny2800
                  Jan 11 '17 at 0:51




                  4




                  4





                  else pass doesn't work because the ternary expression should return a value that can be passed to return. pass is not a valid return value.

                  – Emmett Butler
                  Feb 9 '17 at 23:25





                  else pass doesn't work because the ternary expression should return a value that can be passed to return. pass is not a valid return value.

                  – Emmett Butler
                  Feb 9 '17 at 23:25




                  1




                  1





                  I don't agree that this motivation is the real reason, given that if a_condition: variable = "something" and if a_condition: return variable are legal. So it is essentially an arbitrary syntactic choice of python.

                  – oulenz
                  Mar 24 '18 at 10:40





                  I don't agree that this motivation is the real reason, given that if a_condition: variable = "something" and if a_condition: return variable are legal. So it is essentially an arbitrary syntactic choice of python.

                  – oulenz
                  Mar 24 '18 at 10:40











                  12














                  if <condition>: myList.append('myString')


                  Otherwise, no. Why the need to put it on one line?



                  Note that the "ternary operator" is an operator. Like any operator, it must return something, so how can you have a ternary operator without the else clause? What is it supposed to return if the condition isn't true-like?






                  share|improve this answer




























                    12














                    if <condition>: myList.append('myString')


                    Otherwise, no. Why the need to put it on one line?



                    Note that the "ternary operator" is an operator. Like any operator, it must return something, so how can you have a ternary operator without the else clause? What is it supposed to return if the condition isn't true-like?






                    share|improve this answer


























                      12












                      12








                      12







                      if <condition>: myList.append('myString')


                      Otherwise, no. Why the need to put it on one line?



                      Note that the "ternary operator" is an operator. Like any operator, it must return something, so how can you have a ternary operator without the else clause? What is it supposed to return if the condition isn't true-like?






                      share|improve this answer













                      if <condition>: myList.append('myString')


                      Otherwise, no. Why the need to put it on one line?



                      Note that the "ternary operator" is an operator. Like any operator, it must return something, so how can you have a ternary operator without the else clause? What is it supposed to return if the condition isn't true-like?







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Aug 30 '12 at 14:57









                      mgilsonmgilson

                      215k40425537




                      215k40425537























                          5














                          You are basically asking for do_thing() if <condition> else pass construct (which will throw SyntaxError, if ran). As I have discovered during research for (somewhat) similar question do_thing() if condition else None is as close as you can get (which is just another way to do <condition> and do_thing()). So, to summarize this idea and other answers, here are your options:





                          • if <condition>: myList.append('myString') — seems to be the least 'hacky' (and thus preferred) way

                          • <condition> and myList.append('myString')

                          • myList.append('myString') if <condition> else None






                          share|improve this answer




























                            5














                            You are basically asking for do_thing() if <condition> else pass construct (which will throw SyntaxError, if ran). As I have discovered during research for (somewhat) similar question do_thing() if condition else None is as close as you can get (which is just another way to do <condition> and do_thing()). So, to summarize this idea and other answers, here are your options:





                            • if <condition>: myList.append('myString') — seems to be the least 'hacky' (and thus preferred) way

                            • <condition> and myList.append('myString')

                            • myList.append('myString') if <condition> else None






                            share|improve this answer


























                              5












                              5








                              5







                              You are basically asking for do_thing() if <condition> else pass construct (which will throw SyntaxError, if ran). As I have discovered during research for (somewhat) similar question do_thing() if condition else None is as close as you can get (which is just another way to do <condition> and do_thing()). So, to summarize this idea and other answers, here are your options:





                              • if <condition>: myList.append('myString') — seems to be the least 'hacky' (and thus preferred) way

                              • <condition> and myList.append('myString')

                              • myList.append('myString') if <condition> else None






                              share|improve this answer













                              You are basically asking for do_thing() if <condition> else pass construct (which will throw SyntaxError, if ran). As I have discovered during research for (somewhat) similar question do_thing() if condition else None is as close as you can get (which is just another way to do <condition> and do_thing()). So, to summarize this idea and other answers, here are your options:





                              • if <condition>: myList.append('myString') — seems to be the least 'hacky' (and thus preferred) way

                              • <condition> and myList.append('myString')

                              • myList.append('myString') if <condition> else None







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Jul 10 '18 at 9:30









                              Filipp W.Filipp W.

                              2,08511130




                              2,08511130























                                  3














                                  myList.extend(['myString'] if condition else ) would also work, though it's more work than the other solutions.






                                  share|improve this answer




























                                    3














                                    myList.extend(['myString'] if condition else ) would also work, though it's more work than the other solutions.






                                    share|improve this answer


























                                      3












                                      3








                                      3







                                      myList.extend(['myString'] if condition else ) would also work, though it's more work than the other solutions.






                                      share|improve this answer













                                      myList.extend(['myString'] if condition else ) would also work, though it's more work than the other solutions.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Aug 30 '12 at 15:21









                                      Jake BiesingerJake Biesinger

                                      3,29611719




                                      3,29611719























                                          0














                                          You can do something like this:



                                          myList.append('myString') if <condition> else False


                                          or



                                          myList.append('myString') if <condition> else 0





                                          share|improve this answer




























                                            0














                                            You can do something like this:



                                            myList.append('myString') if <condition> else False


                                            or



                                            myList.append('myString') if <condition> else 0





                                            share|improve this answer


























                                              0












                                              0








                                              0







                                              You can do something like this:



                                              myList.append('myString') if <condition> else False


                                              or



                                              myList.append('myString') if <condition> else 0





                                              share|improve this answer













                                              You can do something like this:



                                              myList.append('myString') if <condition> else False


                                              or



                                              myList.append('myString') if <condition> else 0






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Nov 17 '18 at 4:54









                                              Zachary ChiodiniZachary Chiodini

                                              1




                                              1






























                                                  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%2f12199757%2fpython-ternary-operator-without-else%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

                                                  Bressuire

                                                  Vorschmack

                                                  Quarantine