Python list iterator behavior and next(iterator)What does next() do on a Tensorflow Dataset object?Iterating over every two elements in a listIs calling next(iter) inside for i in iter supported in python?Why doesn't QtConsole echo next()?How is the for-loop able to use a variable that isn't defined yetHow do I efficiently iterate over each entry in a Java Map?How do I check if a list is empty?What are metaclasses in Python?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonDoes Python have a ternary conditional operator?How to make a flat list out of list of lists?Iterate through a HashMapHow do I get the number of elements in a list in Python?How do I concatenate two lists in Python?

How do we know the LHC results are robust?

How can we prove that any integral in the set of non-elementary integrals cannot be expressed in the form of elementary functions?

Why, precisely, is argon used in neutrino experiments?

How do I rename a Linux host without needing to reboot for the rename to take effect?

Applicability of Single Responsibility Principle

Escape a backup date in a file name

Detecting if an element is found inside a container

Crossing the line between justified force and brutality

Did Dumbledore lie to Harry about how long he had James Potter's invisibility cloak when he was examining it? If so, why?

Two monoidal structures and copowering

How can a function with a hole (removable discontinuity) equal a function with no hole?

Do sorcerers' Subtle Spells require a skill check to be unseen?

What happens if you roll doubles 3 times then land on "Go to jail?"

How to write papers efficiently when English isn't my first language?

Did the DC-9 ever use RATO in revenue service?

Implement the Thanos sorting algorithm

What is paid subscription needed for in Mortal Kombat 11?

Is a stroke of luck acceptable after a series of unfavorable events?

How does Loki do this?

You cannot touch me, but I can touch you, who am I?

What is the opposite of 'gravitas'?

Is exact Kanji stroke length important?

Is oxalic acid dihydrate considered a primary acid standard in analytical chemistry?

Roman Numeral Treatment of Suspensions



Python list iterator behavior and next(iterator)


What does next() do on a Tensorflow Dataset object?Iterating over every two elements in a listIs calling next(iter) inside for i in iter supported in python?Why doesn't QtConsole echo next()?How is the for-loop able to use a variable that isn't defined yetHow do I efficiently iterate over each entry in a Java Map?How do I check if a list is empty?What are metaclasses in Python?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonDoes Python have a ternary conditional operator?How to make a flat list out of list of lists?Iterate through a HashMapHow do I get the number of elements in a list in Python?How do I concatenate two lists in Python?













123















Consider:



>>> lst = iter([1,2,3])
>>> next(lst)
1
>>> next(lst)
2


So, advancing the iterator is, as expected, handled by mutating that same object.



This being the case, I would expect:



a = iter(list(range(10)))
for i in a:
print(i)
next(a)


to skip every second element: the call to next should advance the iterator once, then the implicit call made by the loop should advance it a second time - and the result of this second call would be assigned to i.



It doesn't. The loop prints all of the items in the list, without skipping any.



My first thought was that this might happen because the loop calls iter on what it is passed, and this might give an independent iterator - this isn't the case, as we have iter(a) is a.



So, why does next not appear to advance the iterator in this case?










share|improve this question




























    123















    Consider:



    >>> lst = iter([1,2,3])
    >>> next(lst)
    1
    >>> next(lst)
    2


    So, advancing the iterator is, as expected, handled by mutating that same object.



    This being the case, I would expect:



    a = iter(list(range(10)))
    for i in a:
    print(i)
    next(a)


    to skip every second element: the call to next should advance the iterator once, then the implicit call made by the loop should advance it a second time - and the result of this second call would be assigned to i.



    It doesn't. The loop prints all of the items in the list, without skipping any.



    My first thought was that this might happen because the loop calls iter on what it is passed, and this might give an independent iterator - this isn't the case, as we have iter(a) is a.



    So, why does next not appear to advance the iterator in this case?










    share|improve this question


























      123












      123








      123


      24






      Consider:



      >>> lst = iter([1,2,3])
      >>> next(lst)
      1
      >>> next(lst)
      2


      So, advancing the iterator is, as expected, handled by mutating that same object.



      This being the case, I would expect:



      a = iter(list(range(10)))
      for i in a:
      print(i)
      next(a)


      to skip every second element: the call to next should advance the iterator once, then the implicit call made by the loop should advance it a second time - and the result of this second call would be assigned to i.



      It doesn't. The loop prints all of the items in the list, without skipping any.



      My first thought was that this might happen because the loop calls iter on what it is passed, and this might give an independent iterator - this isn't the case, as we have iter(a) is a.



      So, why does next not appear to advance the iterator in this case?










      share|improve this question
















      Consider:



      >>> lst = iter([1,2,3])
      >>> next(lst)
      1
      >>> next(lst)
      2


      So, advancing the iterator is, as expected, handled by mutating that same object.



      This being the case, I would expect:



      a = iter(list(range(10)))
      for i in a:
      print(i)
      next(a)


      to skip every second element: the call to next should advance the iterator once, then the implicit call made by the loop should advance it a second time - and the result of this second call would be assigned to i.



      It doesn't. The loop prints all of the items in the list, without skipping any.



      My first thought was that this might happen because the loop calls iter on what it is passed, and this might give an independent iterator - this isn't the case, as we have iter(a) is a.



      So, why does next not appear to advance the iterator in this case?







      python list iterator iteration






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Sep 4 '17 at 15:05









      Martijn Pieters

      723k14125352341




      723k14125352341










      asked May 29 '13 at 13:17









      lvclvc

      24.7k55089




      24.7k55089






















          6 Answers
          6






          active

          oldest

          votes


















          169














          What you see is the interpreter echoing back the return value of next() in addition to i being printed each iteration:



          >>> a = iter(list(range(10)))
          >>> for i in a:
          ... print(i)
          ... next(a)
          ...
          0
          1
          2
          3
          4
          5
          6
          7
          8
          9


          So 0 is the output of print(i), 1 the return value from next(), echoed by the interactive interpreter, etc. There are just 5 iterations, each iteration resulting in 2 lines being written to the terminal.



          If you assign the output of next() things work as expected:



          >>> a = iter(list(range(10)))
          >>> for i in a:
          ... print(i)
          ... _ = next(a)
          ...
          0
          2
          4
          6
          8


          or print extra information to differentiate the print() output from the interactive interpreter echo:



          >>> a = iter(list(range(10)))
          >>> for i in a:
          ... print('Printing: '.format(i))
          ... next(a)
          ...
          Printing: 0
          1
          Printing: 2
          3
          Printing: 4
          5
          Printing: 6
          7
          Printing: 8
          9


          In other words, next() is working as expected, but because it returns the next value from the iterator, echoed by the interactive interpreter, you are led to believe that the loop has its own iterator copy somehow.






          share|improve this answer




















          • 10





            I was not aware of this behavior from the interpreter. I am glad that I discovered that before losing a lot of time wondering about it while solving some real problem.

            – brandizzi
            May 29 '13 at 13:26






          • 4





            ... *dies*. The worst of it is, I can remember mentioning exactly this interpreter behavior to someone perhaps a week ago.

            – lvc
            May 29 '13 at 13:30











          • interesting. I tried for i in a: next(a) ;print i and thought i would jump to 1 and print 1,3,5,7,9. But still it is 0,2,4,6,8. Why?

            – user2290820
            Jul 6 '13 at 17:16







          • 2





            i was already assigned. next(a) means that the next iteration 2 is assigned to i, then you move a along again, print i, etc.

            – Martijn Pieters
            Jul 6 '13 at 17:18






          • 1





            This doesn't work if n is odd - StopIteration excepetio nis raised when next(a) is called after the list is exausted.

            – Raf
            Mar 1 at 8:55


















          12














          What is happening is that next(a) returns the next value of a, which is printed to the console because it is not affected.



          What you can do is affect a variable with this value:



          >>> a = iter(list(range(10)))
          >>> for i in a:
          ... print(i)
          ... b=next(a)
          ...
          0
          2
          4
          6
          8





          share|improve this answer






























            7














            I find the existing answers a little confusing, because they only indirectly indicate the essential mystifying thing in the code example: both* the "print i" and the "next(a)" are causing their results to be printed.



            Since they're printing alternating elements of the original sequence, and it's unexpected that the "next(a)" statement is printing, it appears as if the "print i" statement is printing all the values.



            In that light, it becomes more clear that assigning the result of "next(a)" to a variable inhibits the printing of its' result, so that just the alternate values that the "i" loop variable are printed. Similarly, making the "print" statement emit something more distinctive disambiguates it, as well.



            (One of the existing answers refutes the others because that answer is having the example code evaluated as a block, so that the interpreter is not reporting the intermediate values for "next(a)".)



            The beguiling thing in answering questions, in general, is being explicit about what is obvious once you know the answer. It can be elusive. Likewise critiquing answers once you understand them. It's interesting...






            share|improve this answer






























              2














              Something is wrong with your Python/Computer.



              a = iter(list(range(10)))
              for i in a:
              print(i)
              next(a)

              >>>
              0
              2
              4
              6
              8


              Works like expected.



              Tested in Python 2.7 and in Python 3+ . Works properly in both






              share|improve this answer


















              • 5





                I get the same result as @lvc (only on IDLE however, when executed as script I get this))

                – jamylak
                May 29 '13 at 13:19







              • 3





                @Inbar Rose Only if you run as script.

                – Quintec
                Apr 16 '14 at 23:19






              • 1





                it is behavior of putting code via interactive shell. If function returns value without being used, interpreter would print it to shell as debug output

                – Reishin
                Jan 29 '18 at 11:28


















              1














              It behaves the way you want if called as a function:



              >>> def test():
              ... a = iter(list(range(10)))
              ... for i in a:
              ... print(i)
              ... next(a)
              ...
              >>> test()
              0
              2
              4
              6
              8





              share|improve this answer






























                1














                For those who still do not understand.



                >>> a = iter(list(range(10)))
                >>> for i in a:
                ... print(i)
                ... next(a)
                ...
                0 # print(i) printed this
                1 # next(a) printed this
                2 # print(i) printed this
                3 # next(a) printed this
                4 # print(i) printed this
                5 # next(a) printed this
                6 # print(i) printed this
                7 # next(a) printed this
                8 # print(i) printed this
                9 # next(a) printed this


                As others have already said, next increases the iterator by 1 as expected. Assigning its returned value to a variable doesn't magically changes its behaviour.






                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%2f16814984%2fpython-list-iterator-behavior-and-nextiterator%23new-answer', 'question_page');

                  );

                  Post as a guest















                  Required, but never shown

























                  6 Answers
                  6






                  active

                  oldest

                  votes








                  6 Answers
                  6






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  169














                  What you see is the interpreter echoing back the return value of next() in addition to i being printed each iteration:



                  >>> a = iter(list(range(10)))
                  >>> for i in a:
                  ... print(i)
                  ... next(a)
                  ...
                  0
                  1
                  2
                  3
                  4
                  5
                  6
                  7
                  8
                  9


                  So 0 is the output of print(i), 1 the return value from next(), echoed by the interactive interpreter, etc. There are just 5 iterations, each iteration resulting in 2 lines being written to the terminal.



                  If you assign the output of next() things work as expected:



                  >>> a = iter(list(range(10)))
                  >>> for i in a:
                  ... print(i)
                  ... _ = next(a)
                  ...
                  0
                  2
                  4
                  6
                  8


                  or print extra information to differentiate the print() output from the interactive interpreter echo:



                  >>> a = iter(list(range(10)))
                  >>> for i in a:
                  ... print('Printing: '.format(i))
                  ... next(a)
                  ...
                  Printing: 0
                  1
                  Printing: 2
                  3
                  Printing: 4
                  5
                  Printing: 6
                  7
                  Printing: 8
                  9


                  In other words, next() is working as expected, but because it returns the next value from the iterator, echoed by the interactive interpreter, you are led to believe that the loop has its own iterator copy somehow.






                  share|improve this answer




















                  • 10





                    I was not aware of this behavior from the interpreter. I am glad that I discovered that before losing a lot of time wondering about it while solving some real problem.

                    – brandizzi
                    May 29 '13 at 13:26






                  • 4





                    ... *dies*. The worst of it is, I can remember mentioning exactly this interpreter behavior to someone perhaps a week ago.

                    – lvc
                    May 29 '13 at 13:30











                  • interesting. I tried for i in a: next(a) ;print i and thought i would jump to 1 and print 1,3,5,7,9. But still it is 0,2,4,6,8. Why?

                    – user2290820
                    Jul 6 '13 at 17:16







                  • 2





                    i was already assigned. next(a) means that the next iteration 2 is assigned to i, then you move a along again, print i, etc.

                    – Martijn Pieters
                    Jul 6 '13 at 17:18






                  • 1





                    This doesn't work if n is odd - StopIteration excepetio nis raised when next(a) is called after the list is exausted.

                    – Raf
                    Mar 1 at 8:55















                  169














                  What you see is the interpreter echoing back the return value of next() in addition to i being printed each iteration:



                  >>> a = iter(list(range(10)))
                  >>> for i in a:
                  ... print(i)
                  ... next(a)
                  ...
                  0
                  1
                  2
                  3
                  4
                  5
                  6
                  7
                  8
                  9


                  So 0 is the output of print(i), 1 the return value from next(), echoed by the interactive interpreter, etc. There are just 5 iterations, each iteration resulting in 2 lines being written to the terminal.



                  If you assign the output of next() things work as expected:



                  >>> a = iter(list(range(10)))
                  >>> for i in a:
                  ... print(i)
                  ... _ = next(a)
                  ...
                  0
                  2
                  4
                  6
                  8


                  or print extra information to differentiate the print() output from the interactive interpreter echo:



                  >>> a = iter(list(range(10)))
                  >>> for i in a:
                  ... print('Printing: '.format(i))
                  ... next(a)
                  ...
                  Printing: 0
                  1
                  Printing: 2
                  3
                  Printing: 4
                  5
                  Printing: 6
                  7
                  Printing: 8
                  9


                  In other words, next() is working as expected, but because it returns the next value from the iterator, echoed by the interactive interpreter, you are led to believe that the loop has its own iterator copy somehow.






                  share|improve this answer




















                  • 10





                    I was not aware of this behavior from the interpreter. I am glad that I discovered that before losing a lot of time wondering about it while solving some real problem.

                    – brandizzi
                    May 29 '13 at 13:26






                  • 4





                    ... *dies*. The worst of it is, I can remember mentioning exactly this interpreter behavior to someone perhaps a week ago.

                    – lvc
                    May 29 '13 at 13:30











                  • interesting. I tried for i in a: next(a) ;print i and thought i would jump to 1 and print 1,3,5,7,9. But still it is 0,2,4,6,8. Why?

                    – user2290820
                    Jul 6 '13 at 17:16







                  • 2





                    i was already assigned. next(a) means that the next iteration 2 is assigned to i, then you move a along again, print i, etc.

                    – Martijn Pieters
                    Jul 6 '13 at 17:18






                  • 1





                    This doesn't work if n is odd - StopIteration excepetio nis raised when next(a) is called after the list is exausted.

                    – Raf
                    Mar 1 at 8:55













                  169












                  169








                  169







                  What you see is the interpreter echoing back the return value of next() in addition to i being printed each iteration:



                  >>> a = iter(list(range(10)))
                  >>> for i in a:
                  ... print(i)
                  ... next(a)
                  ...
                  0
                  1
                  2
                  3
                  4
                  5
                  6
                  7
                  8
                  9


                  So 0 is the output of print(i), 1 the return value from next(), echoed by the interactive interpreter, etc. There are just 5 iterations, each iteration resulting in 2 lines being written to the terminal.



                  If you assign the output of next() things work as expected:



                  >>> a = iter(list(range(10)))
                  >>> for i in a:
                  ... print(i)
                  ... _ = next(a)
                  ...
                  0
                  2
                  4
                  6
                  8


                  or print extra information to differentiate the print() output from the interactive interpreter echo:



                  >>> a = iter(list(range(10)))
                  >>> for i in a:
                  ... print('Printing: '.format(i))
                  ... next(a)
                  ...
                  Printing: 0
                  1
                  Printing: 2
                  3
                  Printing: 4
                  5
                  Printing: 6
                  7
                  Printing: 8
                  9


                  In other words, next() is working as expected, but because it returns the next value from the iterator, echoed by the interactive interpreter, you are led to believe that the loop has its own iterator copy somehow.






                  share|improve this answer















                  What you see is the interpreter echoing back the return value of next() in addition to i being printed each iteration:



                  >>> a = iter(list(range(10)))
                  >>> for i in a:
                  ... print(i)
                  ... next(a)
                  ...
                  0
                  1
                  2
                  3
                  4
                  5
                  6
                  7
                  8
                  9


                  So 0 is the output of print(i), 1 the return value from next(), echoed by the interactive interpreter, etc. There are just 5 iterations, each iteration resulting in 2 lines being written to the terminal.



                  If you assign the output of next() things work as expected:



                  >>> a = iter(list(range(10)))
                  >>> for i in a:
                  ... print(i)
                  ... _ = next(a)
                  ...
                  0
                  2
                  4
                  6
                  8


                  or print extra information to differentiate the print() output from the interactive interpreter echo:



                  >>> a = iter(list(range(10)))
                  >>> for i in a:
                  ... print('Printing: '.format(i))
                  ... next(a)
                  ...
                  Printing: 0
                  1
                  Printing: 2
                  3
                  Printing: 4
                  5
                  Printing: 6
                  7
                  Printing: 8
                  9


                  In other words, next() is working as expected, but because it returns the next value from the iterator, echoed by the interactive interpreter, you are led to believe that the loop has its own iterator copy somehow.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Oct 6 '15 at 16:07

























                  answered May 29 '13 at 13:21









                  Martijn PietersMartijn Pieters

                  723k14125352341




                  723k14125352341







                  • 10





                    I was not aware of this behavior from the interpreter. I am glad that I discovered that before losing a lot of time wondering about it while solving some real problem.

                    – brandizzi
                    May 29 '13 at 13:26






                  • 4





                    ... *dies*. The worst of it is, I can remember mentioning exactly this interpreter behavior to someone perhaps a week ago.

                    – lvc
                    May 29 '13 at 13:30











                  • interesting. I tried for i in a: next(a) ;print i and thought i would jump to 1 and print 1,3,5,7,9. But still it is 0,2,4,6,8. Why?

                    – user2290820
                    Jul 6 '13 at 17:16







                  • 2





                    i was already assigned. next(a) means that the next iteration 2 is assigned to i, then you move a along again, print i, etc.

                    – Martijn Pieters
                    Jul 6 '13 at 17:18






                  • 1





                    This doesn't work if n is odd - StopIteration excepetio nis raised when next(a) is called after the list is exausted.

                    – Raf
                    Mar 1 at 8:55












                  • 10





                    I was not aware of this behavior from the interpreter. I am glad that I discovered that before losing a lot of time wondering about it while solving some real problem.

                    – brandizzi
                    May 29 '13 at 13:26






                  • 4





                    ... *dies*. The worst of it is, I can remember mentioning exactly this interpreter behavior to someone perhaps a week ago.

                    – lvc
                    May 29 '13 at 13:30











                  • interesting. I tried for i in a: next(a) ;print i and thought i would jump to 1 and print 1,3,5,7,9. But still it is 0,2,4,6,8. Why?

                    – user2290820
                    Jul 6 '13 at 17:16







                  • 2





                    i was already assigned. next(a) means that the next iteration 2 is assigned to i, then you move a along again, print i, etc.

                    – Martijn Pieters
                    Jul 6 '13 at 17:18






                  • 1





                    This doesn't work if n is odd - StopIteration excepetio nis raised when next(a) is called after the list is exausted.

                    – Raf
                    Mar 1 at 8:55







                  10




                  10





                  I was not aware of this behavior from the interpreter. I am glad that I discovered that before losing a lot of time wondering about it while solving some real problem.

                  – brandizzi
                  May 29 '13 at 13:26





                  I was not aware of this behavior from the interpreter. I am glad that I discovered that before losing a lot of time wondering about it while solving some real problem.

                  – brandizzi
                  May 29 '13 at 13:26




                  4




                  4





                  ... *dies*. The worst of it is, I can remember mentioning exactly this interpreter behavior to someone perhaps a week ago.

                  – lvc
                  May 29 '13 at 13:30





                  ... *dies*. The worst of it is, I can remember mentioning exactly this interpreter behavior to someone perhaps a week ago.

                  – lvc
                  May 29 '13 at 13:30













                  interesting. I tried for i in a: next(a) ;print i and thought i would jump to 1 and print 1,3,5,7,9. But still it is 0,2,4,6,8. Why?

                  – user2290820
                  Jul 6 '13 at 17:16






                  interesting. I tried for i in a: next(a) ;print i and thought i would jump to 1 and print 1,3,5,7,9. But still it is 0,2,4,6,8. Why?

                  – user2290820
                  Jul 6 '13 at 17:16





                  2




                  2





                  i was already assigned. next(a) means that the next iteration 2 is assigned to i, then you move a along again, print i, etc.

                  – Martijn Pieters
                  Jul 6 '13 at 17:18





                  i was already assigned. next(a) means that the next iteration 2 is assigned to i, then you move a along again, print i, etc.

                  – Martijn Pieters
                  Jul 6 '13 at 17:18




                  1




                  1





                  This doesn't work if n is odd - StopIteration excepetio nis raised when next(a) is called after the list is exausted.

                  – Raf
                  Mar 1 at 8:55





                  This doesn't work if n is odd - StopIteration excepetio nis raised when next(a) is called after the list is exausted.

                  – Raf
                  Mar 1 at 8:55













                  12














                  What is happening is that next(a) returns the next value of a, which is printed to the console because it is not affected.



                  What you can do is affect a variable with this value:



                  >>> a = iter(list(range(10)))
                  >>> for i in a:
                  ... print(i)
                  ... b=next(a)
                  ...
                  0
                  2
                  4
                  6
                  8





                  share|improve this answer



























                    12














                    What is happening is that next(a) returns the next value of a, which is printed to the console because it is not affected.



                    What you can do is affect a variable with this value:



                    >>> a = iter(list(range(10)))
                    >>> for i in a:
                    ... print(i)
                    ... b=next(a)
                    ...
                    0
                    2
                    4
                    6
                    8





                    share|improve this answer

























                      12












                      12








                      12







                      What is happening is that next(a) returns the next value of a, which is printed to the console because it is not affected.



                      What you can do is affect a variable with this value:



                      >>> a = iter(list(range(10)))
                      >>> for i in a:
                      ... print(i)
                      ... b=next(a)
                      ...
                      0
                      2
                      4
                      6
                      8





                      share|improve this answer













                      What is happening is that next(a) returns the next value of a, which is printed to the console because it is not affected.



                      What you can do is affect a variable with this value:



                      >>> a = iter(list(range(10)))
                      >>> for i in a:
                      ... print(i)
                      ... b=next(a)
                      ...
                      0
                      2
                      4
                      6
                      8






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered May 29 '13 at 13:23









                      njzk2njzk2

                      32.9k45092




                      32.9k45092





















                          7














                          I find the existing answers a little confusing, because they only indirectly indicate the essential mystifying thing in the code example: both* the "print i" and the "next(a)" are causing their results to be printed.



                          Since they're printing alternating elements of the original sequence, and it's unexpected that the "next(a)" statement is printing, it appears as if the "print i" statement is printing all the values.



                          In that light, it becomes more clear that assigning the result of "next(a)" to a variable inhibits the printing of its' result, so that just the alternate values that the "i" loop variable are printed. Similarly, making the "print" statement emit something more distinctive disambiguates it, as well.



                          (One of the existing answers refutes the others because that answer is having the example code evaluated as a block, so that the interpreter is not reporting the intermediate values for "next(a)".)



                          The beguiling thing in answering questions, in general, is being explicit about what is obvious once you know the answer. It can be elusive. Likewise critiquing answers once you understand them. It's interesting...






                          share|improve this answer



























                            7














                            I find the existing answers a little confusing, because they only indirectly indicate the essential mystifying thing in the code example: both* the "print i" and the "next(a)" are causing their results to be printed.



                            Since they're printing alternating elements of the original sequence, and it's unexpected that the "next(a)" statement is printing, it appears as if the "print i" statement is printing all the values.



                            In that light, it becomes more clear that assigning the result of "next(a)" to a variable inhibits the printing of its' result, so that just the alternate values that the "i" loop variable are printed. Similarly, making the "print" statement emit something more distinctive disambiguates it, as well.



                            (One of the existing answers refutes the others because that answer is having the example code evaluated as a block, so that the interpreter is not reporting the intermediate values for "next(a)".)



                            The beguiling thing in answering questions, in general, is being explicit about what is obvious once you know the answer. It can be elusive. Likewise critiquing answers once you understand them. It's interesting...






                            share|improve this answer

























                              7












                              7








                              7







                              I find the existing answers a little confusing, because they only indirectly indicate the essential mystifying thing in the code example: both* the "print i" and the "next(a)" are causing their results to be printed.



                              Since they're printing alternating elements of the original sequence, and it's unexpected that the "next(a)" statement is printing, it appears as if the "print i" statement is printing all the values.



                              In that light, it becomes more clear that assigning the result of "next(a)" to a variable inhibits the printing of its' result, so that just the alternate values that the "i" loop variable are printed. Similarly, making the "print" statement emit something more distinctive disambiguates it, as well.



                              (One of the existing answers refutes the others because that answer is having the example code evaluated as a block, so that the interpreter is not reporting the intermediate values for "next(a)".)



                              The beguiling thing in answering questions, in general, is being explicit about what is obvious once you know the answer. It can be elusive. Likewise critiquing answers once you understand them. It's interesting...






                              share|improve this answer













                              I find the existing answers a little confusing, because they only indirectly indicate the essential mystifying thing in the code example: both* the "print i" and the "next(a)" are causing their results to be printed.



                              Since they're printing alternating elements of the original sequence, and it's unexpected that the "next(a)" statement is printing, it appears as if the "print i" statement is printing all the values.



                              In that light, it becomes more clear that assigning the result of "next(a)" to a variable inhibits the printing of its' result, so that just the alternate values that the "i" loop variable are printed. Similarly, making the "print" statement emit something more distinctive disambiguates it, as well.



                              (One of the existing answers refutes the others because that answer is having the example code evaluated as a block, so that the interpreter is not reporting the intermediate values for "next(a)".)



                              The beguiling thing in answering questions, in general, is being explicit about what is obvious once you know the answer. It can be elusive. Likewise critiquing answers once you understand them. It's interesting...







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered May 30 '13 at 14:32









                              klmklm

                              45236




                              45236





















                                  2














                                  Something is wrong with your Python/Computer.



                                  a = iter(list(range(10)))
                                  for i in a:
                                  print(i)
                                  next(a)

                                  >>>
                                  0
                                  2
                                  4
                                  6
                                  8


                                  Works like expected.



                                  Tested in Python 2.7 and in Python 3+ . Works properly in both






                                  share|improve this answer


















                                  • 5





                                    I get the same result as @lvc (only on IDLE however, when executed as script I get this))

                                    – jamylak
                                    May 29 '13 at 13:19







                                  • 3





                                    @Inbar Rose Only if you run as script.

                                    – Quintec
                                    Apr 16 '14 at 23:19






                                  • 1





                                    it is behavior of putting code via interactive shell. If function returns value without being used, interpreter would print it to shell as debug output

                                    – Reishin
                                    Jan 29 '18 at 11:28















                                  2














                                  Something is wrong with your Python/Computer.



                                  a = iter(list(range(10)))
                                  for i in a:
                                  print(i)
                                  next(a)

                                  >>>
                                  0
                                  2
                                  4
                                  6
                                  8


                                  Works like expected.



                                  Tested in Python 2.7 and in Python 3+ . Works properly in both






                                  share|improve this answer


















                                  • 5





                                    I get the same result as @lvc (only on IDLE however, when executed as script I get this))

                                    – jamylak
                                    May 29 '13 at 13:19







                                  • 3





                                    @Inbar Rose Only if you run as script.

                                    – Quintec
                                    Apr 16 '14 at 23:19






                                  • 1





                                    it is behavior of putting code via interactive shell. If function returns value without being used, interpreter would print it to shell as debug output

                                    – Reishin
                                    Jan 29 '18 at 11:28













                                  2












                                  2








                                  2







                                  Something is wrong with your Python/Computer.



                                  a = iter(list(range(10)))
                                  for i in a:
                                  print(i)
                                  next(a)

                                  >>>
                                  0
                                  2
                                  4
                                  6
                                  8


                                  Works like expected.



                                  Tested in Python 2.7 and in Python 3+ . Works properly in both






                                  share|improve this answer













                                  Something is wrong with your Python/Computer.



                                  a = iter(list(range(10)))
                                  for i in a:
                                  print(i)
                                  next(a)

                                  >>>
                                  0
                                  2
                                  4
                                  6
                                  8


                                  Works like expected.



                                  Tested in Python 2.7 and in Python 3+ . Works properly in both







                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered May 29 '13 at 13:19









                                  Inbar RoseInbar Rose

                                  26.3k1669101




                                  26.3k1669101







                                  • 5





                                    I get the same result as @lvc (only on IDLE however, when executed as script I get this))

                                    – jamylak
                                    May 29 '13 at 13:19







                                  • 3





                                    @Inbar Rose Only if you run as script.

                                    – Quintec
                                    Apr 16 '14 at 23:19






                                  • 1





                                    it is behavior of putting code via interactive shell. If function returns value without being used, interpreter would print it to shell as debug output

                                    – Reishin
                                    Jan 29 '18 at 11:28












                                  • 5





                                    I get the same result as @lvc (only on IDLE however, when executed as script I get this))

                                    – jamylak
                                    May 29 '13 at 13:19







                                  • 3





                                    @Inbar Rose Only if you run as script.

                                    – Quintec
                                    Apr 16 '14 at 23:19






                                  • 1





                                    it is behavior of putting code via interactive shell. If function returns value without being used, interpreter would print it to shell as debug output

                                    – Reishin
                                    Jan 29 '18 at 11:28







                                  5




                                  5





                                  I get the same result as @lvc (only on IDLE however, when executed as script I get this))

                                  – jamylak
                                  May 29 '13 at 13:19






                                  I get the same result as @lvc (only on IDLE however, when executed as script I get this))

                                  – jamylak
                                  May 29 '13 at 13:19





                                  3




                                  3





                                  @Inbar Rose Only if you run as script.

                                  – Quintec
                                  Apr 16 '14 at 23:19





                                  @Inbar Rose Only if you run as script.

                                  – Quintec
                                  Apr 16 '14 at 23:19




                                  1




                                  1





                                  it is behavior of putting code via interactive shell. If function returns value without being used, interpreter would print it to shell as debug output

                                  – Reishin
                                  Jan 29 '18 at 11:28





                                  it is behavior of putting code via interactive shell. If function returns value without being used, interpreter would print it to shell as debug output

                                  – Reishin
                                  Jan 29 '18 at 11:28











                                  1














                                  It behaves the way you want if called as a function:



                                  >>> def test():
                                  ... a = iter(list(range(10)))
                                  ... for i in a:
                                  ... print(i)
                                  ... next(a)
                                  ...
                                  >>> test()
                                  0
                                  2
                                  4
                                  6
                                  8





                                  share|improve this answer



























                                    1














                                    It behaves the way you want if called as a function:



                                    >>> def test():
                                    ... a = iter(list(range(10)))
                                    ... for i in a:
                                    ... print(i)
                                    ... next(a)
                                    ...
                                    >>> test()
                                    0
                                    2
                                    4
                                    6
                                    8





                                    share|improve this answer

























                                      1












                                      1








                                      1







                                      It behaves the way you want if called as a function:



                                      >>> def test():
                                      ... a = iter(list(range(10)))
                                      ... for i in a:
                                      ... print(i)
                                      ... next(a)
                                      ...
                                      >>> test()
                                      0
                                      2
                                      4
                                      6
                                      8





                                      share|improve this answer













                                      It behaves the way you want if called as a function:



                                      >>> def test():
                                      ... a = iter(list(range(10)))
                                      ... for i in a:
                                      ... print(i)
                                      ... next(a)
                                      ...
                                      >>> test()
                                      0
                                      2
                                      4
                                      6
                                      8






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Oct 3 '15 at 17:39









                                      burmerburmer

                                      644




                                      644





















                                          1














                                          For those who still do not understand.



                                          >>> a = iter(list(range(10)))
                                          >>> for i in a:
                                          ... print(i)
                                          ... next(a)
                                          ...
                                          0 # print(i) printed this
                                          1 # next(a) printed this
                                          2 # print(i) printed this
                                          3 # next(a) printed this
                                          4 # print(i) printed this
                                          5 # next(a) printed this
                                          6 # print(i) printed this
                                          7 # next(a) printed this
                                          8 # print(i) printed this
                                          9 # next(a) printed this


                                          As others have already said, next increases the iterator by 1 as expected. Assigning its returned value to a variable doesn't magically changes its behaviour.






                                          share|improve this answer



























                                            1














                                            For those who still do not understand.



                                            >>> a = iter(list(range(10)))
                                            >>> for i in a:
                                            ... print(i)
                                            ... next(a)
                                            ...
                                            0 # print(i) printed this
                                            1 # next(a) printed this
                                            2 # print(i) printed this
                                            3 # next(a) printed this
                                            4 # print(i) printed this
                                            5 # next(a) printed this
                                            6 # print(i) printed this
                                            7 # next(a) printed this
                                            8 # print(i) printed this
                                            9 # next(a) printed this


                                            As others have already said, next increases the iterator by 1 as expected. Assigning its returned value to a variable doesn't magically changes its behaviour.






                                            share|improve this answer

























                                              1












                                              1








                                              1







                                              For those who still do not understand.



                                              >>> a = iter(list(range(10)))
                                              >>> for i in a:
                                              ... print(i)
                                              ... next(a)
                                              ...
                                              0 # print(i) printed this
                                              1 # next(a) printed this
                                              2 # print(i) printed this
                                              3 # next(a) printed this
                                              4 # print(i) printed this
                                              5 # next(a) printed this
                                              6 # print(i) printed this
                                              7 # next(a) printed this
                                              8 # print(i) printed this
                                              9 # next(a) printed this


                                              As others have already said, next increases the iterator by 1 as expected. Assigning its returned value to a variable doesn't magically changes its behaviour.






                                              share|improve this answer













                                              For those who still do not understand.



                                              >>> a = iter(list(range(10)))
                                              >>> for i in a:
                                              ... print(i)
                                              ... next(a)
                                              ...
                                              0 # print(i) printed this
                                              1 # next(a) printed this
                                              2 # print(i) printed this
                                              3 # next(a) printed this
                                              4 # print(i) printed this
                                              5 # next(a) printed this
                                              6 # print(i) printed this
                                              7 # next(a) printed this
                                              8 # print(i) printed this
                                              9 # next(a) printed this


                                              As others have already said, next increases the iterator by 1 as expected. Assigning its returned value to a variable doesn't magically changes its behaviour.







                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Jul 10 '18 at 6:48









                                              WesleyWesley

                                              344316




                                              344316



























                                                  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%2f16814984%2fpython-list-iterator-behavior-and-nextiterator%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

                                                  Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                                  Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                                                  Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript