Compare if one tuple is greater when mixing `str` and `None` types in Python





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







1















I have two lists of tuples that have a mix of str and None types and need to compare them considering None to be greater.



a = tuple([None, 4])
b = tuple(['pencil', 12])

a > b


Results in:




TypeError: '>' not supported between instances of 'NoneType' and 'str'




How can I compare these items without getting that error?










share|improve this question





























    1















    I have two lists of tuples that have a mix of str and None types and need to compare them considering None to be greater.



    a = tuple([None, 4])
    b = tuple(['pencil', 12])

    a > b


    Results in:




    TypeError: '>' not supported between instances of 'NoneType' and 'str'




    How can I compare these items without getting that error?










    share|improve this question

























      1












      1








      1








      I have two lists of tuples that have a mix of str and None types and need to compare them considering None to be greater.



      a = tuple([None, 4])
      b = tuple(['pencil', 12])

      a > b


      Results in:




      TypeError: '>' not supported between instances of 'NoneType' and 'str'




      How can I compare these items without getting that error?










      share|improve this question














      I have two lists of tuples that have a mix of str and None types and need to compare them considering None to be greater.



      a = tuple([None, 4])
      b = tuple(['pencil', 12])

      a > b


      Results in:




      TypeError: '>' not supported between instances of 'NoneType' and 'str'




      How can I compare these items without getting that error?







      python tuples comparison






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 16 '18 at 16:56









      ZevZev

      2,25111227




      2,25111227
























          2 Answers
          2






          active

          oldest

          votes


















          1














          You can also subclass tuple and create your own tuple class with the __lt__ and __gt__ methods appropriately implemented:



          class MyTuple(tuple):
          def __lt__(self, other):
          for s, o in zip(self, other):
          if s == o:
          continue
          if s is None:
          return False
          if o is None:
          return True
          return super().__lt__(other)

          def __gt__(self, other):
          return not self.__lt__(other)


          a = MyTuple([None, 4])
          b = MyTuple(['pencil', 12])

          print(a < b) # False
          print(a > b) # True





          share|improve this answer



















          • 1





            Gotcha, I like that use of super to fall back on.

            – Zev
            Nov 16 '18 at 18:10











          • My only question with doing it this way is that I think it'd loop through the tuple an extra time when there isn't a None value.

            – Zev
            Nov 16 '18 at 18:16






          • 1





            That is correct. However, you're doing the same thing in your approach as well (item1 > item2 in the try block) for the case where there is a None present.

            – slider
            Nov 16 '18 at 18:20






          • 1





            Good point! It depends on the use case (whether None is likely to be present). I think I'll end up putting the return super().__lt__(other) in a try-except block for my use case.

            – Zev
            Nov 16 '18 at 18:24



















          0














          You can replace item > item2 with a function like this:



          def compare_tuples(item1, item2):
          try:
          return item1 > item2
          # if they can be compared, just do so directly
          except TypeError:
          for field1, field2 in zip(item1, item2):
          # otherwise go through the fields in the tuples
          # and compare them checking if they are none
          if field1 == field2:
          continue
          if field1 is None:
          return True
          if field2 is None:
          return False





          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%2f53342272%2fcompare-if-one-tuple-is-greater-when-mixing-str-and-none-types-in-python%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









            1














            You can also subclass tuple and create your own tuple class with the __lt__ and __gt__ methods appropriately implemented:



            class MyTuple(tuple):
            def __lt__(self, other):
            for s, o in zip(self, other):
            if s == o:
            continue
            if s is None:
            return False
            if o is None:
            return True
            return super().__lt__(other)

            def __gt__(self, other):
            return not self.__lt__(other)


            a = MyTuple([None, 4])
            b = MyTuple(['pencil', 12])

            print(a < b) # False
            print(a > b) # True





            share|improve this answer



















            • 1





              Gotcha, I like that use of super to fall back on.

              – Zev
              Nov 16 '18 at 18:10











            • My only question with doing it this way is that I think it'd loop through the tuple an extra time when there isn't a None value.

              – Zev
              Nov 16 '18 at 18:16






            • 1





              That is correct. However, you're doing the same thing in your approach as well (item1 > item2 in the try block) for the case where there is a None present.

              – slider
              Nov 16 '18 at 18:20






            • 1





              Good point! It depends on the use case (whether None is likely to be present). I think I'll end up putting the return super().__lt__(other) in a try-except block for my use case.

              – Zev
              Nov 16 '18 at 18:24
















            1














            You can also subclass tuple and create your own tuple class with the __lt__ and __gt__ methods appropriately implemented:



            class MyTuple(tuple):
            def __lt__(self, other):
            for s, o in zip(self, other):
            if s == o:
            continue
            if s is None:
            return False
            if o is None:
            return True
            return super().__lt__(other)

            def __gt__(self, other):
            return not self.__lt__(other)


            a = MyTuple([None, 4])
            b = MyTuple(['pencil', 12])

            print(a < b) # False
            print(a > b) # True





            share|improve this answer



















            • 1





              Gotcha, I like that use of super to fall back on.

              – Zev
              Nov 16 '18 at 18:10











            • My only question with doing it this way is that I think it'd loop through the tuple an extra time when there isn't a None value.

              – Zev
              Nov 16 '18 at 18:16






            • 1





              That is correct. However, you're doing the same thing in your approach as well (item1 > item2 in the try block) for the case where there is a None present.

              – slider
              Nov 16 '18 at 18:20






            • 1





              Good point! It depends on the use case (whether None is likely to be present). I think I'll end up putting the return super().__lt__(other) in a try-except block for my use case.

              – Zev
              Nov 16 '18 at 18:24














            1












            1








            1







            You can also subclass tuple and create your own tuple class with the __lt__ and __gt__ methods appropriately implemented:



            class MyTuple(tuple):
            def __lt__(self, other):
            for s, o in zip(self, other):
            if s == o:
            continue
            if s is None:
            return False
            if o is None:
            return True
            return super().__lt__(other)

            def __gt__(self, other):
            return not self.__lt__(other)


            a = MyTuple([None, 4])
            b = MyTuple(['pencil', 12])

            print(a < b) # False
            print(a > b) # True





            share|improve this answer













            You can also subclass tuple and create your own tuple class with the __lt__ and __gt__ methods appropriately implemented:



            class MyTuple(tuple):
            def __lt__(self, other):
            for s, o in zip(self, other):
            if s == o:
            continue
            if s is None:
            return False
            if o is None:
            return True
            return super().__lt__(other)

            def __gt__(self, other):
            return not self.__lt__(other)


            a = MyTuple([None, 4])
            b = MyTuple(['pencil', 12])

            print(a < b) # False
            print(a > b) # True






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 16 '18 at 17:29









            sliderslider

            8,56811331




            8,56811331








            • 1





              Gotcha, I like that use of super to fall back on.

              – Zev
              Nov 16 '18 at 18:10











            • My only question with doing it this way is that I think it'd loop through the tuple an extra time when there isn't a None value.

              – Zev
              Nov 16 '18 at 18:16






            • 1





              That is correct. However, you're doing the same thing in your approach as well (item1 > item2 in the try block) for the case where there is a None present.

              – slider
              Nov 16 '18 at 18:20






            • 1





              Good point! It depends on the use case (whether None is likely to be present). I think I'll end up putting the return super().__lt__(other) in a try-except block for my use case.

              – Zev
              Nov 16 '18 at 18:24














            • 1





              Gotcha, I like that use of super to fall back on.

              – Zev
              Nov 16 '18 at 18:10











            • My only question with doing it this way is that I think it'd loop through the tuple an extra time when there isn't a None value.

              – Zev
              Nov 16 '18 at 18:16






            • 1





              That is correct. However, you're doing the same thing in your approach as well (item1 > item2 in the try block) for the case where there is a None present.

              – slider
              Nov 16 '18 at 18:20






            • 1





              Good point! It depends on the use case (whether None is likely to be present). I think I'll end up putting the return super().__lt__(other) in a try-except block for my use case.

              – Zev
              Nov 16 '18 at 18:24








            1




            1





            Gotcha, I like that use of super to fall back on.

            – Zev
            Nov 16 '18 at 18:10





            Gotcha, I like that use of super to fall back on.

            – Zev
            Nov 16 '18 at 18:10













            My only question with doing it this way is that I think it'd loop through the tuple an extra time when there isn't a None value.

            – Zev
            Nov 16 '18 at 18:16





            My only question with doing it this way is that I think it'd loop through the tuple an extra time when there isn't a None value.

            – Zev
            Nov 16 '18 at 18:16




            1




            1





            That is correct. However, you're doing the same thing in your approach as well (item1 > item2 in the try block) for the case where there is a None present.

            – slider
            Nov 16 '18 at 18:20





            That is correct. However, you're doing the same thing in your approach as well (item1 > item2 in the try block) for the case where there is a None present.

            – slider
            Nov 16 '18 at 18:20




            1




            1





            Good point! It depends on the use case (whether None is likely to be present). I think I'll end up putting the return super().__lt__(other) in a try-except block for my use case.

            – Zev
            Nov 16 '18 at 18:24





            Good point! It depends on the use case (whether None is likely to be present). I think I'll end up putting the return super().__lt__(other) in a try-except block for my use case.

            – Zev
            Nov 16 '18 at 18:24













            0














            You can replace item > item2 with a function like this:



            def compare_tuples(item1, item2):
            try:
            return item1 > item2
            # if they can be compared, just do so directly
            except TypeError:
            for field1, field2 in zip(item1, item2):
            # otherwise go through the fields in the tuples
            # and compare them checking if they are none
            if field1 == field2:
            continue
            if field1 is None:
            return True
            if field2 is None:
            return False





            share|improve this answer




























              0














              You can replace item > item2 with a function like this:



              def compare_tuples(item1, item2):
              try:
              return item1 > item2
              # if they can be compared, just do so directly
              except TypeError:
              for field1, field2 in zip(item1, item2):
              # otherwise go through the fields in the tuples
              # and compare them checking if they are none
              if field1 == field2:
              continue
              if field1 is None:
              return True
              if field2 is None:
              return False





              share|improve this answer


























                0












                0








                0







                You can replace item > item2 with a function like this:



                def compare_tuples(item1, item2):
                try:
                return item1 > item2
                # if they can be compared, just do so directly
                except TypeError:
                for field1, field2 in zip(item1, item2):
                # otherwise go through the fields in the tuples
                # and compare them checking if they are none
                if field1 == field2:
                continue
                if field1 is None:
                return True
                if field2 is None:
                return False





                share|improve this answer













                You can replace item > item2 with a function like this:



                def compare_tuples(item1, item2):
                try:
                return item1 > item2
                # if they can be compared, just do so directly
                except TypeError:
                for field1, field2 in zip(item1, item2):
                # otherwise go through the fields in the tuples
                # and compare them checking if they are none
                if field1 == field2:
                continue
                if field1 is None:
                return True
                if field2 is None:
                return False






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 16 '18 at 16:56









                ZevZev

                2,25111227




                2,25111227






























                    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%2f53342272%2fcompare-if-one-tuple-is-greater-when-mixing-str-and-none-types-in-python%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

                    Florida Star v. B. J. F.

                    Danny Elfman

                    Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues