Python: next in for loopCalling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?How to get the current time in PythonAccessing the index in 'for' loops?Iterating over dictionaries using 'for' loopsDoes Python have a string 'contains' substring method?

Why are electrically insulating heatsinks so rare? Is it just cost?

Can an x86 CPU running in real mode be considered to be basically an 8086 CPU?

Modeling an IPv4 Address

Today is the Center

What is the word for reserving something for yourself before others do?

How is the claim "I am in New York only if I am in America" the same as "If I am in New York, then I am in America?

In Japanese, what’s the difference between “Tonari ni” (となりに) and “Tsugi” (つぎ)? When would you use one over the other?

How did the USSR manage to innovate in an environment characterized by government censorship and high bureaucracy?

Font hinting is lost in Chrome-like browsers (for some languages )

Has the BBC provided arguments for saying Brexit being cancelled is unlikely?

What are these boxed doors outside store fronts in New York?

Do VLANs within a subnet need to have their own subnet for router on a stick?

Can I ask the recruiters in my resume to put the reason why I am rejected?

Accidentally leaked the solution to an assignment, what to do now? (I'm the prof)

Can divisibility rules for digits be generalized to sum of digits

How can I make my BBEG immortal short of making them a Lich or Vampire?

How much RAM could one put in a typical 80386 setup?

Is it unprofessional to ask if a job posting on GlassDoor is real?

Collect Fourier series terms

Why can't I see bouncing of a switch on an oscilloscope?

Why don't electron-positron collisions release infinite energy?

LaTeX closing $ signs makes cursor jump

"You are your self first supporter", a more proper way to say it

How does strength of boric acid solution increase in presence of salicylic acid?



Python: next in for loop


Calling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?How to get the current time in PythonAccessing the index in 'for' loops?Iterating over dictionaries using 'for' loopsDoes Python have a string 'contains' substring method?






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








6















I want to use next to skip one or more items returned from a generator. Here is a simplified example designed to skip one item per loop (in actual use, I'd test n and depending on the result, may repeat the next() and the generator is from a package I don't control):



def gen():
for i in range(10):
yield i

for g in gen():
n = next(gen())
print(g, n)


I expected the result to be



0 1
2 3


etc.



Instead I got



0 0
1 0


etc.



What am I doing wrong?










share|improve this question




























    6















    I want to use next to skip one or more items returned from a generator. Here is a simplified example designed to skip one item per loop (in actual use, I'd test n and depending on the result, may repeat the next() and the generator is from a package I don't control):



    def gen():
    for i in range(10):
    yield i

    for g in gen():
    n = next(gen())
    print(g, n)


    I expected the result to be



    0 1
    2 3


    etc.



    Instead I got



    0 0
    1 0


    etc.



    What am I doing wrong?










    share|improve this question
























      6












      6








      6


      1






      I want to use next to skip one or more items returned from a generator. Here is a simplified example designed to skip one item per loop (in actual use, I'd test n and depending on the result, may repeat the next() and the generator is from a package I don't control):



      def gen():
      for i in range(10):
      yield i

      for g in gen():
      n = next(gen())
      print(g, n)


      I expected the result to be



      0 1
      2 3


      etc.



      Instead I got



      0 0
      1 0


      etc.



      What am I doing wrong?










      share|improve this question














      I want to use next to skip one or more items returned from a generator. Here is a simplified example designed to skip one item per loop (in actual use, I'd test n and depending on the result, may repeat the next() and the generator is from a package I don't control):



      def gen():
      for i in range(10):
      yield i

      for g in gen():
      n = next(gen())
      print(g, n)


      I expected the result to be



      0 1
      2 3


      etc.



      Instead I got



      0 0
      1 0


      etc.



      What am I doing wrong?







      python generator next






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 1 hour ago









      foosionfoosion

      3,325144990




      3,325144990






















          1 Answer
          1






          active

          oldest

          votes


















          5














          You're making a new generator each time you call gen(). Each new generator starts from 0.



          Instead, you can call it once and capture the return value.



          def gen():
          for i in range(10):
          yield i

          x = gen()
          for g in x:
          n = next(x)
          print(g, 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%2f55553886%2fpython-next-in-for-loop%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            5














            You're making a new generator each time you call gen(). Each new generator starts from 0.



            Instead, you can call it once and capture the return value.



            def gen():
            for i in range(10):
            yield i

            x = gen()
            for g in x:
            n = next(x)
            print(g, n)





            share|improve this answer



























              5














              You're making a new generator each time you call gen(). Each new generator starts from 0.



              Instead, you can call it once and capture the return value.



              def gen():
              for i in range(10):
              yield i

              x = gen()
              for g in x:
              n = next(x)
              print(g, n)





              share|improve this answer

























                5












                5








                5







                You're making a new generator each time you call gen(). Each new generator starts from 0.



                Instead, you can call it once and capture the return value.



                def gen():
                for i in range(10):
                yield i

                x = gen()
                for g in x:
                n = next(x)
                print(g, n)





                share|improve this answer













                You're making a new generator each time you call gen(). Each new generator starts from 0.



                Instead, you can call it once and capture the return value.



                def gen():
                for i in range(10):
                yield i

                x = gen()
                for g in x:
                n = next(x)
                print(g, n)






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 1 hour ago









                khelwoodkhelwood

                32.2k74465




                32.2k74465





























                    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%2f55553886%2fpython-next-in-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

                    Are there any AGPL-style licences that require source code modifications to be public? Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?Force derivative works to be publicAre there any GPL like licenses for Apple App Store?Do you violate the GPL if you provide source code that cannot be compiled?GPL - is it distribution to use libraries in an appliance loaned to customers?Distributing App for free which uses GPL'ed codeModifications of server software under GPL, with web/CLI interfaceDoes using an AGPLv3-licensed library prevent me from dual-licensing my own source code?Can I publish only select code under GPLv3 from a private project?Is there published precedent regarding the scope of covered work that uses AGPL software?If MIT licensed code links to GPL licensed code what should be the license of the resulting binary program?If I use a public API endpoint that has its source code licensed under AGPL in my app, do I need to disclose my source?

                    2013 GY136 Descoberta | Órbita | Referências Menu de navegação«List Of Centaurs and Scattered-Disk Objects»«List of Known Trans-Neptunian Objects»

                    Button changing it's text & action. Good or terrible? The 2019 Stack Overflow Developer Survey Results Are Inchanging text on user mouseoverShould certain functions be “hard to find” for powerusers to discover?Custom liking function - do I need user login?Using different checkbox style for different checkbox behaviorBest Practices: Save and Exit in Software UIInteraction with remote validated formMore efficient UI to progress the user through a complicated process?Designing a popup notice for a gameShould bulk-editing functions be hidden until a table row is selected, or is there a better solution?Is it bad practice to disable (replace) the context menu?