How does sum function work in python with for loop












3















I was using sum function in pyhton, and i am clear about it's general structure sum(iterable, start) , but i am unable to get the logic behind the following code



test = sum(5 for i in range(5) )
print("output: ", test)


output: 25



Please can anyone describe what is happening here, basically here 5 is getting multiplied with 5, and same pattern is there for every sample input.










share|improve this question





























    3















    I was using sum function in pyhton, and i am clear about it's general structure sum(iterable, start) , but i am unable to get the logic behind the following code



    test = sum(5 for i in range(5) )
    print("output: ", test)


    output: 25



    Please can anyone describe what is happening here, basically here 5 is getting multiplied with 5, and same pattern is there for every sample input.










    share|improve this question



























      3












      3








      3








      I was using sum function in pyhton, and i am clear about it's general structure sum(iterable, start) , but i am unable to get the logic behind the following code



      test = sum(5 for i in range(5) )
      print("output: ", test)


      output: 25



      Please can anyone describe what is happening here, basically here 5 is getting multiplied with 5, and same pattern is there for every sample input.










      share|improve this question
















      I was using sum function in pyhton, and i am clear about it's general structure sum(iterable, start) , but i am unable to get the logic behind the following code



      test = sum(5 for i in range(5) )
      print("output: ", test)


      output: 25



      Please can anyone describe what is happening here, basically here 5 is getting multiplied with 5, and same pattern is there for every sample input.







      python python-3.x sum generator iterable






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 31 '18 at 3:09









      jpp

      99.5k2161110




      99.5k2161110










      asked Dec 31 '18 at 2:57









      alok456alok456

      437




      437
























          3 Answers
          3






          active

          oldest

          votes


















          2














          Your code is shorthand for:



          test = sum((5 for i in range(5)))


          The removal of extra parentheses is syntactic sugar: it has no impact on your algorithm.



          The (5 for i in range(5)) component is a generator expression which, on each iteration, yields the value 5. Your generator expression has 5 iterations in total, as defined by range(5). Therefore, the generator expression yields 5 exactly 5 times.



          sum, as the docs indicate, accepts any iterable, even those not held entirely in memory. Generators, and by extension generator expressions, are memory efficient. Therefore, your logic will sum 5 exactly 5 times, which equals 25.



          A convention when you don't use a variable in a closed loop is to denote that variable by underscore (_), so usually you'll see your code written as:



          test = sum(5 for _ in range(5))





          share|improve this answer



















          • 1





            Thanks a lot, now i am able to understand it clearly.

            – alok456
            Dec 31 '18 at 3:37



















          0














          You can add a list to the sum function so you can make something like this:



          test = sum((1,23,5,6,100))
          print("output: ", test)


          And you get 135.



          So with your "for loop" you get a list and put that list to the sum function and you get the sum of the list. The real sum function uses yield insight and use every value and sum them up.






          share|improve this answer































            0














            Basically, it is summing 5 repeativily for every "i" on range(5). Meaning, this code is equivalent to n*5, being n the size of range(n).






            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%2f53983152%2fhow-does-sum-function-work-in-python-with-for-loop%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              2














              Your code is shorthand for:



              test = sum((5 for i in range(5)))


              The removal of extra parentheses is syntactic sugar: it has no impact on your algorithm.



              The (5 for i in range(5)) component is a generator expression which, on each iteration, yields the value 5. Your generator expression has 5 iterations in total, as defined by range(5). Therefore, the generator expression yields 5 exactly 5 times.



              sum, as the docs indicate, accepts any iterable, even those not held entirely in memory. Generators, and by extension generator expressions, are memory efficient. Therefore, your logic will sum 5 exactly 5 times, which equals 25.



              A convention when you don't use a variable in a closed loop is to denote that variable by underscore (_), so usually you'll see your code written as:



              test = sum(5 for _ in range(5))





              share|improve this answer



















              • 1





                Thanks a lot, now i am able to understand it clearly.

                – alok456
                Dec 31 '18 at 3:37
















              2














              Your code is shorthand for:



              test = sum((5 for i in range(5)))


              The removal of extra parentheses is syntactic sugar: it has no impact on your algorithm.



              The (5 for i in range(5)) component is a generator expression which, on each iteration, yields the value 5. Your generator expression has 5 iterations in total, as defined by range(5). Therefore, the generator expression yields 5 exactly 5 times.



              sum, as the docs indicate, accepts any iterable, even those not held entirely in memory. Generators, and by extension generator expressions, are memory efficient. Therefore, your logic will sum 5 exactly 5 times, which equals 25.



              A convention when you don't use a variable in a closed loop is to denote that variable by underscore (_), so usually you'll see your code written as:



              test = sum(5 for _ in range(5))





              share|improve this answer



















              • 1





                Thanks a lot, now i am able to understand it clearly.

                – alok456
                Dec 31 '18 at 3:37














              2












              2








              2







              Your code is shorthand for:



              test = sum((5 for i in range(5)))


              The removal of extra parentheses is syntactic sugar: it has no impact on your algorithm.



              The (5 for i in range(5)) component is a generator expression which, on each iteration, yields the value 5. Your generator expression has 5 iterations in total, as defined by range(5). Therefore, the generator expression yields 5 exactly 5 times.



              sum, as the docs indicate, accepts any iterable, even those not held entirely in memory. Generators, and by extension generator expressions, are memory efficient. Therefore, your logic will sum 5 exactly 5 times, which equals 25.



              A convention when you don't use a variable in a closed loop is to denote that variable by underscore (_), so usually you'll see your code written as:



              test = sum(5 for _ in range(5))





              share|improve this answer













              Your code is shorthand for:



              test = sum((5 for i in range(5)))


              The removal of extra parentheses is syntactic sugar: it has no impact on your algorithm.



              The (5 for i in range(5)) component is a generator expression which, on each iteration, yields the value 5. Your generator expression has 5 iterations in total, as defined by range(5). Therefore, the generator expression yields 5 exactly 5 times.



              sum, as the docs indicate, accepts any iterable, even those not held entirely in memory. Generators, and by extension generator expressions, are memory efficient. Therefore, your logic will sum 5 exactly 5 times, which equals 25.



              A convention when you don't use a variable in a closed loop is to denote that variable by underscore (_), so usually you'll see your code written as:



              test = sum(5 for _ in range(5))






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Dec 31 '18 at 3:04









              jppjpp

              99.5k2161110




              99.5k2161110








              • 1





                Thanks a lot, now i am able to understand it clearly.

                – alok456
                Dec 31 '18 at 3:37














              • 1





                Thanks a lot, now i am able to understand it clearly.

                – alok456
                Dec 31 '18 at 3:37








              1




              1





              Thanks a lot, now i am able to understand it clearly.

              – alok456
              Dec 31 '18 at 3:37





              Thanks a lot, now i am able to understand it clearly.

              – alok456
              Dec 31 '18 at 3:37













              0














              You can add a list to the sum function so you can make something like this:



              test = sum((1,23,5,6,100))
              print("output: ", test)


              And you get 135.



              So with your "for loop" you get a list and put that list to the sum function and you get the sum of the list. The real sum function uses yield insight and use every value and sum them up.






              share|improve this answer




























                0














                You can add a list to the sum function so you can make something like this:



                test = sum((1,23,5,6,100))
                print("output: ", test)


                And you get 135.



                So with your "for loop" you get a list and put that list to the sum function and you get the sum of the list. The real sum function uses yield insight and use every value and sum them up.






                share|improve this answer


























                  0












                  0








                  0







                  You can add a list to the sum function so you can make something like this:



                  test = sum((1,23,5,6,100))
                  print("output: ", test)


                  And you get 135.



                  So with your "for loop" you get a list and put that list to the sum function and you get the sum of the list. The real sum function uses yield insight and use every value and sum them up.






                  share|improve this answer













                  You can add a list to the sum function so you can make something like this:



                  test = sum((1,23,5,6,100))
                  print("output: ", test)


                  And you get 135.



                  So with your "for loop" you get a list and put that list to the sum function and you get the sum of the list. The real sum function uses yield insight and use every value and sum them up.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Dec 31 '18 at 3:02









                  StonyStony

                  20.2k135264




                  20.2k135264























                      0














                      Basically, it is summing 5 repeativily for every "i" on range(5). Meaning, this code is equivalent to n*5, being n the size of range(n).






                      share|improve this answer




























                        0














                        Basically, it is summing 5 repeativily for every "i" on range(5). Meaning, this code is equivalent to n*5, being n the size of range(n).






                        share|improve this answer


























                          0












                          0








                          0







                          Basically, it is summing 5 repeativily for every "i" on range(5). Meaning, this code is equivalent to n*5, being n the size of range(n).






                          share|improve this answer













                          Basically, it is summing 5 repeativily for every "i" on range(5). Meaning, this code is equivalent to n*5, being n the size of range(n).







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Dec 31 '18 at 3:06









                          Felipe MoreiraFelipe Moreira

                          11




                          11






























                              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%2f53983152%2fhow-does-sum-function-work-in-python-with-for-loop%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

                              Mossoró

                              Error while reading .h5 file using the rhdf5 package in R

                              Pushsharp Apns notification error: 'InvalidToken'