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?

How is it possible for user's password to be changed after storage was encrypted? (on OS X, Android)

Draw simple lines in Inkscape

I see my dog run

A newer friend of my brother's gave him a load of baseball cards that are supposedly extremely valuable. Is this a scam?

How can I fix this gap between bookcases I made?

What do you call something that goes against the spirit of the law, but is legal when interpreting the law to the letter?

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

Extreme, but not acceptable situation and I can't start the work tomorrow morning

Can a German sentence have two subjects?

Can you lasso down a wizard who is using the Levitate spell?

Concept of linear mappings are confusing me

What does "enim et" mean?

What Brexit solution does the DUP want?

Is there a minimum number of transactions in a block?

Example of a relative pronoun

I’m planning on buying a laser printer but concerned about the life cycle of toner in the machine

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

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

Could a US political party gain complete control over the government by removing checks & balances?

Why do we use polarized capacitor?

Can I make popcorn with any corn?

Why did the Germans forbid the possession of pet pigeons in Rostov-on-Don in 1941?

What is GPS' 19 year rollover and does it present a cybersecurity issue?

Motorized valve interfering with button?



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;








7















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




























    7















    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
























      7












      7








      7


      2






      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 yesterday









      foosionfoosion

      3,330144990




      3,330144990






















          1 Answer
          1






          active

          oldest

          votes


















          8














          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









            8














            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



























              8














              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

























                8












                8








                8







                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 yesterday









                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

                    Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

                    Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

                    Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form