Index of maximum value of a list











up vote
0
down vote

favorite












I need to implement a function that returns the index of the maximum value of a list. I wrote that but it doesn't work. Could someone tell me why?



def maximum_index(lst):
maximum=0
index=0
for i,value in enumerate(lst):
if value>maximum:
maximum=value
index=i
return index









share|improve this question









New contributor




Sophie Gérard is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • It also should return None when the list is empty but I'm not sure how to do it
    – Sophie Gérard
    Nov 17 at 14:37










  • start with if not lst: return None
    – Chris_Rands
    Nov 17 at 14:39






  • 2




    your current method fails if the maximum value is <0
    – Chris_Rands
    Nov 17 at 14:39






  • 2




    As it was already mentionned on your previous question on SO, 'it doesn't work' is not an accurate enough description of the problem your encountered. If you get an error, please include the complete error traceback. If you don't get the expected result for some data, include the relevant data that exhibits the faulty behavior, as well as the output you get vs the expected one.
    – Thierry Lathuille
    Nov 17 at 14:48















up vote
0
down vote

favorite












I need to implement a function that returns the index of the maximum value of a list. I wrote that but it doesn't work. Could someone tell me why?



def maximum_index(lst):
maximum=0
index=0
for i,value in enumerate(lst):
if value>maximum:
maximum=value
index=i
return index









share|improve this question









New contributor




Sophie Gérard is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • It also should return None when the list is empty but I'm not sure how to do it
    – Sophie Gérard
    Nov 17 at 14:37










  • start with if not lst: return None
    – Chris_Rands
    Nov 17 at 14:39






  • 2




    your current method fails if the maximum value is <0
    – Chris_Rands
    Nov 17 at 14:39






  • 2




    As it was already mentionned on your previous question on SO, 'it doesn't work' is not an accurate enough description of the problem your encountered. If you get an error, please include the complete error traceback. If you don't get the expected result for some data, include the relevant data that exhibits the faulty behavior, as well as the output you get vs the expected one.
    – Thierry Lathuille
    Nov 17 at 14:48













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I need to implement a function that returns the index of the maximum value of a list. I wrote that but it doesn't work. Could someone tell me why?



def maximum_index(lst):
maximum=0
index=0
for i,value in enumerate(lst):
if value>maximum:
maximum=value
index=i
return index









share|improve this question









New contributor




Sophie Gérard is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











I need to implement a function that returns the index of the maximum value of a list. I wrote that but it doesn't work. Could someone tell me why?



def maximum_index(lst):
maximum=0
index=0
for i,value in enumerate(lst):
if value>maximum:
maximum=value
index=i
return index






python






share|improve this question









New contributor




Sophie Gérard is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Sophie Gérard is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited Nov 17 at 15:00









Ayxan

1,06715




1,06715






New contributor




Sophie Gérard is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked Nov 17 at 14:36









Sophie Gérard

13




13




New contributor




Sophie Gérard is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Sophie Gérard is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Sophie Gérard is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • It also should return None when the list is empty but I'm not sure how to do it
    – Sophie Gérard
    Nov 17 at 14:37










  • start with if not lst: return None
    – Chris_Rands
    Nov 17 at 14:39






  • 2




    your current method fails if the maximum value is <0
    – Chris_Rands
    Nov 17 at 14:39






  • 2




    As it was already mentionned on your previous question on SO, 'it doesn't work' is not an accurate enough description of the problem your encountered. If you get an error, please include the complete error traceback. If you don't get the expected result for some data, include the relevant data that exhibits the faulty behavior, as well as the output you get vs the expected one.
    – Thierry Lathuille
    Nov 17 at 14:48


















  • It also should return None when the list is empty but I'm not sure how to do it
    – Sophie Gérard
    Nov 17 at 14:37










  • start with if not lst: return None
    – Chris_Rands
    Nov 17 at 14:39






  • 2




    your current method fails if the maximum value is <0
    – Chris_Rands
    Nov 17 at 14:39






  • 2




    As it was already mentionned on your previous question on SO, 'it doesn't work' is not an accurate enough description of the problem your encountered. If you get an error, please include the complete error traceback. If you don't get the expected result for some data, include the relevant data that exhibits the faulty behavior, as well as the output you get vs the expected one.
    – Thierry Lathuille
    Nov 17 at 14:48
















It also should return None when the list is empty but I'm not sure how to do it
– Sophie Gérard
Nov 17 at 14:37




It also should return None when the list is empty but I'm not sure how to do it
– Sophie Gérard
Nov 17 at 14:37












start with if not lst: return None
– Chris_Rands
Nov 17 at 14:39




start with if not lst: return None
– Chris_Rands
Nov 17 at 14:39




2




2




your current method fails if the maximum value is <0
– Chris_Rands
Nov 17 at 14:39




your current method fails if the maximum value is <0
– Chris_Rands
Nov 17 at 14:39




2




2




As it was already mentionned on your previous question on SO, 'it doesn't work' is not an accurate enough description of the problem your encountered. If you get an error, please include the complete error traceback. If you don't get the expected result for some data, include the relevant data that exhibits the faulty behavior, as well as the output you get vs the expected one.
– Thierry Lathuille
Nov 17 at 14:48




As it was already mentionned on your previous question on SO, 'it doesn't work' is not an accurate enough description of the problem your encountered. If you get an error, please include the complete error traceback. If you don't get the expected result for some data, include the relevant data that exhibits the faulty behavior, as well as the output you get vs the expected one.
– Thierry Lathuille
Nov 17 at 14:48












4 Answers
4






active

oldest

votes

















up vote
0
down vote



accepted










Your code seemed fine to me. I think the only problem is your indentation and that you only check positive values. The way it is indented everything is outside of the function.



Also I added Chris_Rands suggestion of starting with a check, whether the list is empty. Here you go:



def maximum_index(lst):
if not lst:
return None

first = True
maximum=0
index=0
for i,value in enumerate(lst):
if value > maximum or first:
first = False
maximum = value
index = i
return index





share|improve this answer























  • This still fails if the maximum is < 0
    – Thierry Lathuille
    Nov 17 at 14:44










  • Yeah, I oversaw that as well. Made an edit to fix this.
    – FChris
    Nov 17 at 14:47


















up vote
0
down vote













a better way is to just use max directly:



max(enumerate(lst), key=lambda pair: pair[1], default=(None, None))[0]


enumerate yields (idx, value) tuples for the list, the key checks for the max based on only the value, and then [0] grabs the idx from the tuple from enumerate






share|improve this answer




























    up vote
    0
    down vote













    Use max built-in function to find the maximum value and index method to find its index:



    def maximum_index(lst):
    if (not lst):
    return None
    return lst.index(max(lst))


    Test it:



    print(maximum_index([1, 2, 3, 9, 8, 7, 6]))
    print(maximum_index())


    Output:



    3
    None





    share|improve this answer






























      up vote
      0
      down vote













      If you aren't allowed to use max and index as suggested by @Ayxan, you should start the loop assuming that the first element is the max, and then updating accordingly.



      def maximum_index(lst):
      if not lst: # check if list is empty
      return None

      # initialize maximum and index
      index = None
      maximum = lst[0]

      # loop and update
      for i, value in enumerate(lst):
      if value > maximum:
      maximum = value
      index = i

      # return index
      return index


      alist = [5, 6, 1, 199, -1, 0, 12]
      print(maximum_index(alist))
      print(maximum_index())





      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',
        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
        });


        }
        });






        Sophie Gérard is a new contributor. Be nice, and check out our Code of Conduct.










         

        draft saved


        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53352216%2findex-of-maximum-value-of-a-list%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        0
        down vote



        accepted










        Your code seemed fine to me. I think the only problem is your indentation and that you only check positive values. The way it is indented everything is outside of the function.



        Also I added Chris_Rands suggestion of starting with a check, whether the list is empty. Here you go:



        def maximum_index(lst):
        if not lst:
        return None

        first = True
        maximum=0
        index=0
        for i,value in enumerate(lst):
        if value > maximum or first:
        first = False
        maximum = value
        index = i
        return index





        share|improve this answer























        • This still fails if the maximum is < 0
          – Thierry Lathuille
          Nov 17 at 14:44










        • Yeah, I oversaw that as well. Made an edit to fix this.
          – FChris
          Nov 17 at 14:47















        up vote
        0
        down vote



        accepted










        Your code seemed fine to me. I think the only problem is your indentation and that you only check positive values. The way it is indented everything is outside of the function.



        Also I added Chris_Rands suggestion of starting with a check, whether the list is empty. Here you go:



        def maximum_index(lst):
        if not lst:
        return None

        first = True
        maximum=0
        index=0
        for i,value in enumerate(lst):
        if value > maximum or first:
        first = False
        maximum = value
        index = i
        return index





        share|improve this answer























        • This still fails if the maximum is < 0
          – Thierry Lathuille
          Nov 17 at 14:44










        • Yeah, I oversaw that as well. Made an edit to fix this.
          – FChris
          Nov 17 at 14:47













        up vote
        0
        down vote



        accepted







        up vote
        0
        down vote



        accepted






        Your code seemed fine to me. I think the only problem is your indentation and that you only check positive values. The way it is indented everything is outside of the function.



        Also I added Chris_Rands suggestion of starting with a check, whether the list is empty. Here you go:



        def maximum_index(lst):
        if not lst:
        return None

        first = True
        maximum=0
        index=0
        for i,value in enumerate(lst):
        if value > maximum or first:
        first = False
        maximum = value
        index = i
        return index





        share|improve this answer














        Your code seemed fine to me. I think the only problem is your indentation and that you only check positive values. The way it is indented everything is outside of the function.



        Also I added Chris_Rands suggestion of starting with a check, whether the list is empty. Here you go:



        def maximum_index(lst):
        if not lst:
        return None

        first = True
        maximum=0
        index=0
        for i,value in enumerate(lst):
        if value > maximum or first:
        first = False
        maximum = value
        index = i
        return index






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 17 at 14:47

























        answered Nov 17 at 14:43









        FChris

        928




        928












        • This still fails if the maximum is < 0
          – Thierry Lathuille
          Nov 17 at 14:44










        • Yeah, I oversaw that as well. Made an edit to fix this.
          – FChris
          Nov 17 at 14:47


















        • This still fails if the maximum is < 0
          – Thierry Lathuille
          Nov 17 at 14:44










        • Yeah, I oversaw that as well. Made an edit to fix this.
          – FChris
          Nov 17 at 14:47
















        This still fails if the maximum is < 0
        – Thierry Lathuille
        Nov 17 at 14:44




        This still fails if the maximum is < 0
        – Thierry Lathuille
        Nov 17 at 14:44












        Yeah, I oversaw that as well. Made an edit to fix this.
        – FChris
        Nov 17 at 14:47




        Yeah, I oversaw that as well. Made an edit to fix this.
        – FChris
        Nov 17 at 14:47












        up vote
        0
        down vote













        a better way is to just use max directly:



        max(enumerate(lst), key=lambda pair: pair[1], default=(None, None))[0]


        enumerate yields (idx, value) tuples for the list, the key checks for the max based on only the value, and then [0] grabs the idx from the tuple from enumerate






        share|improve this answer

























          up vote
          0
          down vote













          a better way is to just use max directly:



          max(enumerate(lst), key=lambda pair: pair[1], default=(None, None))[0]


          enumerate yields (idx, value) tuples for the list, the key checks for the max based on only the value, and then [0] grabs the idx from the tuple from enumerate






          share|improve this answer























            up vote
            0
            down vote










            up vote
            0
            down vote









            a better way is to just use max directly:



            max(enumerate(lst), key=lambda pair: pair[1], default=(None, None))[0]


            enumerate yields (idx, value) tuples for the list, the key checks for the max based on only the value, and then [0] grabs the idx from the tuple from enumerate






            share|improve this answer












            a better way is to just use max directly:



            max(enumerate(lst), key=lambda pair: pair[1], default=(None, None))[0]


            enumerate yields (idx, value) tuples for the list, the key checks for the max based on only the value, and then [0] grabs the idx from the tuple from enumerate







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 17 at 14:49









            acushner

            5,3671826




            5,3671826






















                up vote
                0
                down vote













                Use max built-in function to find the maximum value and index method to find its index:



                def maximum_index(lst):
                if (not lst):
                return None
                return lst.index(max(lst))


                Test it:



                print(maximum_index([1, 2, 3, 9, 8, 7, 6]))
                print(maximum_index())


                Output:



                3
                None





                share|improve this answer



























                  up vote
                  0
                  down vote













                  Use max built-in function to find the maximum value and index method to find its index:



                  def maximum_index(lst):
                  if (not lst):
                  return None
                  return lst.index(max(lst))


                  Test it:



                  print(maximum_index([1, 2, 3, 9, 8, 7, 6]))
                  print(maximum_index())


                  Output:



                  3
                  None





                  share|improve this answer

























                    up vote
                    0
                    down vote










                    up vote
                    0
                    down vote









                    Use max built-in function to find the maximum value and index method to find its index:



                    def maximum_index(lst):
                    if (not lst):
                    return None
                    return lst.index(max(lst))


                    Test it:



                    print(maximum_index([1, 2, 3, 9, 8, 7, 6]))
                    print(maximum_index())


                    Output:



                    3
                    None





                    share|improve this answer














                    Use max built-in function to find the maximum value and index method to find its index:



                    def maximum_index(lst):
                    if (not lst):
                    return None
                    return lst.index(max(lst))


                    Test it:



                    print(maximum_index([1, 2, 3, 9, 8, 7, 6]))
                    print(maximum_index())


                    Output:



                    3
                    None






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 17 at 14:51

























                    answered Nov 17 at 14:44









                    Ayxan

                    1,06715




                    1,06715






















                        up vote
                        0
                        down vote













                        If you aren't allowed to use max and index as suggested by @Ayxan, you should start the loop assuming that the first element is the max, and then updating accordingly.



                        def maximum_index(lst):
                        if not lst: # check if list is empty
                        return None

                        # initialize maximum and index
                        index = None
                        maximum = lst[0]

                        # loop and update
                        for i, value in enumerate(lst):
                        if value > maximum:
                        maximum = value
                        index = i

                        # return index
                        return index


                        alist = [5, 6, 1, 199, -1, 0, 12]
                        print(maximum_index(alist))
                        print(maximum_index())





                        share|improve this answer



























                          up vote
                          0
                          down vote













                          If you aren't allowed to use max and index as suggested by @Ayxan, you should start the loop assuming that the first element is the max, and then updating accordingly.



                          def maximum_index(lst):
                          if not lst: # check if list is empty
                          return None

                          # initialize maximum and index
                          index = None
                          maximum = lst[0]

                          # loop and update
                          for i, value in enumerate(lst):
                          if value > maximum:
                          maximum = value
                          index = i

                          # return index
                          return index


                          alist = [5, 6, 1, 199, -1, 0, 12]
                          print(maximum_index(alist))
                          print(maximum_index())





                          share|improve this answer

























                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            If you aren't allowed to use max and index as suggested by @Ayxan, you should start the loop assuming that the first element is the max, and then updating accordingly.



                            def maximum_index(lst):
                            if not lst: # check if list is empty
                            return None

                            # initialize maximum and index
                            index = None
                            maximum = lst[0]

                            # loop and update
                            for i, value in enumerate(lst):
                            if value > maximum:
                            maximum = value
                            index = i

                            # return index
                            return index


                            alist = [5, 6, 1, 199, -1, 0, 12]
                            print(maximum_index(alist))
                            print(maximum_index())





                            share|improve this answer














                            If you aren't allowed to use max and index as suggested by @Ayxan, you should start the loop assuming that the first element is the max, and then updating accordingly.



                            def maximum_index(lst):
                            if not lst: # check if list is empty
                            return None

                            # initialize maximum and index
                            index = None
                            maximum = lst[0]

                            # loop and update
                            for i, value in enumerate(lst):
                            if value > maximum:
                            maximum = value
                            index = i

                            # return index
                            return index


                            alist = [5, 6, 1, 199, -1, 0, 12]
                            print(maximum_index(alist))
                            print(maximum_index())






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 17 at 15:55

























                            answered Nov 17 at 14:52









                            sal

                            1,4841412




                            1,4841412






















                                Sophie Gérard is a new contributor. Be nice, and check out our Code of Conduct.










                                 

                                draft saved


                                draft discarded


















                                Sophie Gérard is a new contributor. Be nice, and check out our Code of Conduct.













                                Sophie Gérard is a new contributor. Be nice, and check out our Code of Conduct.












                                Sophie Gérard is a new contributor. Be nice, and check out our Code of Conduct.















                                 


                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53352216%2findex-of-maximum-value-of-a-list%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

                                Costa Masnaga

                                Fotorealismo

                                Sidney Franklin