The expression (sum(row) for row in M) creates what's called a generator. This generator will evaluate the expression (sum(row)) once for each row in M. However, the generator doesn't do anything yet, we've just set it up.

The statement next(G) actually runs the generator on M. So, if you run next(G) once, you'll get the sum of the first row. If you run it again, you'll get the sum of the second row, and so on.

>>> M = [[1,2,3],
...      [4,5,6],
...      [7,8,9]]
>>> 
>>> G = (sum(row) for row in M) # create a generator of row sums
>>> next(G) # Run the iteration protocol
6
>>> next(G)
15
>>> next(G)
24

See also:

  • Documentation on generators
  • Documentation on yield expressions (with some info about generators)
Answer from jtbandes on Stack Overflow
🌐
W3Schools
w3schools.com › python › ref_func_next.asp
Python next() Function
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Training ... mylist = iter(["apple", "banana", "cherry"]) x = next(mylist) print(x) x = next(mylist) print(x) x = next(mylist) print(x) Try it Yourself »
🌐
Python documentation
docs.python.org › 3 › library › functions.html
Built-in Functions — Python 3.14.6 documentation
Retrieve the next item from the iterator by calling its __next__() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised. ... This is the ultimate base class of all other classes.
Discussions

Python: next() function - Stack Overflow
Since I'm an absolute beginner, and the author hasn't provided any explanation of the example or the next() function, I don't understand what the code is doing. More on stackoverflow.com
🌐 stackoverflow.com
python - __next__ in generators and iterators and what is a method-wrapper? - Stack Overflow
I was reading about generator and iterators and the role of __next__() . '__next__' in dir(mygen). is true '__next__' in dir(mylist), is false As I looked deeper into it, '__next__' in dir (... More on stackoverflow.com
🌐 stackoverflow.com
Confused with __iter__ and __next__ for python classes?
It so you can write something like for item in Fibonacci(number_list): When using for x in y: ... statement, iter(y) (or y.__iter__()?) is called. Both iterables and iterators (which are also iterables) must have __iter__ method. Iterators' __iter__ method is supposed just return the iterator itself. Iterators must also have __next__ method. More on reddit.com
🌐 r/learnpython
12
2
November 12, 2022
next() method in python: is the definition correct? - Stack Overflow
with open('some.txt', 'r') as input_file: #read the file starting from the second line. for line in input_file: print line The code is self-explanatory. However, I didn't know why it More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-next-method
Python next() method - GeeksforGeeks
December 19, 2025 - The next() function returns the next item from an iterator. If there are no more items, it raises a StopIteration error, unless you provide a default value.
🌐
Programiz
programiz.com › python-programming › methods › built-in › next
Python next()
# the next element is the first element marks_1 = next(iterator_marks) print(marks_1)
🌐
Real Python
realpython.com › ref › builtin-functions › next
next() | Python’s Built-in Functions – Real Python
The .__next__() method processes the current number and returns its square value. When there are no more items, .__next__() raises the StopIteration exception. ... In this tutorial, you'll learn what iterators and iterables are in Python.
Top answer
1 of 2
79

The expression (sum(row) for row in M) creates what's called a generator. This generator will evaluate the expression (sum(row)) once for each row in M. However, the generator doesn't do anything yet, we've just set it up.

The statement next(G) actually runs the generator on M. So, if you run next(G) once, you'll get the sum of the first row. If you run it again, you'll get the sum of the second row, and so on.

>>> M = [[1,2,3],
...      [4,5,6],
...      [7,8,9]]
>>> 
>>> G = (sum(row) for row in M) # create a generator of row sums
>>> next(G) # Run the iteration protocol
6
>>> next(G)
15
>>> next(G)
24

See also:

  • Documentation on generators
  • Documentation on yield expressions (with some info about generators)
2 of 2
10

If you've come that far, then you should already know how a common for-in statement works.

The following statement:

for row in M: print row

would see M as a sequence of 3 rows (sub sequences) consisting of 3 items each, and iterate through M, outputting each row on the matrix:

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

You knew that, well...

You can see Generators just as some syntactic sugar around for-in loops. Forget about the sum() call, and type something like this on IDLE:

G = (row for row in M)
print G
for a in G: print a

You see, the Generator cannot be directly represented as text, not just as a sequence can be. But, you can iterate through a Generator as if it were a sequence.

You'll find some big differences then, but the basics are that you can use a generator not to return just the value of each item in the sequence, but the result of any expression. In the tutorial's example, the expression is sum(row).

Try the following and see what happens:

G = ("("+str(row[2])+";"+str(row[1])+";"+str(row[0])+")" for row in M)
G.next()
G.next()
G.next()
Find elsewhere
🌐
FavTutor
favtutor.com › blogs › next-function-python
Python next() function: Syntax, Example & Advantages
April 27, 2023 - The next() function is an in-built function in Python that is used on iterating operations and helps to return the next item from the iterators. The next item in the collection is fetched using this method.
Top answer
1 of 3
57

The special methods __iter__ and __next__ are part of the iterator protocol to create iterator types. For this purpose, you have to differentiate between two separate things: Iterables and iterators.

Iterables are things that can be iterated, usually, these are some kind of container elements that contain items. Common examples are lists, tuples, or dictionaries.

In order to iterate an iterable, you use an iterator. An iterator is the object that helps you iterate through the container. For example, when iterating a list, the iterator essentially keeps track of which index you are currently at.

To get an iterator, the __iter__ method is called on the iterable. This is like a factory method that returns a new iterator for this specific iterable. A type having a __iter__ method defined, turns it into an iterable.

The iterator generally needs a single method, __next__, which returns the next item for the iteration. In addition, to make the protocol easier to use, every iterator should also be an iterable, returning itself in the __iter__ method.

As a quick example, this would be a possible iterator implementation for a list:

class ListIterator:
    def __init__ (self, lst):
        self.lst = lst
        self.idx = 0

    def __iter__ (self):
        return self

    def __next__ (self):
        try:
            item = self.lst[self.idx]
        except IndexError:
            raise StopIteration()
        self.idx += 1
        return item

The list implementation could then simply return ListIterator(self) from the __iter__ method. Of course, the actual implementation for lists is done in C, so this looks a bit different. But the idea is the same.

Iterators are used invisibly in various places in Python. For example a for loop:

for item in lst:
    print(item)

This is kind of the same to the following:

lst_iterator = iter(lst) # this just calls `lst.__iter__()`
while True:
    try:
        item = next(lst_iterator) # lst_iterator.__next__()
    except StopIteration:
        break
    else:
        print(item)

So the for loop requests an iterator from the iterable object, and then calls __next__ on that iterable until it hits the StopIteration exception. That this happens under the surface is also the reason why you would want iterators to implement the __iter__ as well: Otherwise you could never loop over an iterator.


As for generators, what people usually refer to is actually a generator function, i.e. some function definition that has yield statements. Once you call that generator function, you get back a generator. A generator is esentially just an iterator, albeit a fancy one (since it does more than move through a container). As an iterator, it has a __next__ method to “generate” the next element, and a __iter__ method to return itself.


An example generator function would be the following:

def exampleGenerator():
    yield 1
    print('After 1')
    yield 2
    print('After 2')

The function body containing a yield statement turns this into a generator function. That means that when you call exampleGenerator() you get back a generator object. Generator objects implement the iterator protocol, so we can call __next__ on it (or use the the next() function as above):

>>> x = exampleGenerator()
>>> next(x)
1
>>> next(x)
After 1
2
>>> next(x)
After 2
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    next(x)
StopIteration

Note that the first next() call did not print anything yet. This is the special thing about generators: They are lazy and only evaluate as much as necessary to get the next item from the iterable. Only with the second next() call, we get the first printed line from the function body. And we need another next() call to exhaust the iterable (since there’s not another value yielded).

But apart from that laziness, generators just act like iterables. You even get a StopIteration exception at the end, which allows generators (and generator functions) to be used as for loop sources and wherever “normal” iterables can be used.

The big benefit of generators and their laziness is the ability to generate stuff on demand. A nice analogy for this is endless scrolling on websites: You can scroll down item after after (calling next() on the generator), and every once in a while, the website will have to query a backend to retrieve more items for you to scroll through. Ideally, this happens without you noticing. And that’s exactly what a generator does. It even allows for things like this:

def counter():
    x = 0
    while True:
        x += 1
        yield x

Non-lazy, this would be impossible to compute since this is an infinite loop. But lazily, as a generator, it’s possible to consume this iterative one item after an item. I originally wanted to spare you from implementing this generator as a fully custom iterator type, but in this case, this actually isn’t too difficult, so here it goes:

class CounterGenerator:
    def __init__ (self):
        self.x = 0

    def __iter__ (self):
        return self

    def __next__ (self):
        self.x += 1
        return self.x
2 of 3
5

Why is __next__ only available to list but only to __iter__() and mygen but not mylist. How does __iter__() call __next__ when we are stepping through the list using list-comprehension.

Because lists have a separate object that is returned from iter to handle iteration, this objects __iter__ is consecutively called.

So, for lists:

iter(l) is l # False, returns <list-iterator object at..>

While, for generators:

iter(g) is g # True, its the same object

In looping constructs, iter is first going to get called on the target object to be looped over. iter calls __iter__ and an iterator is expected to be returned; its __next__ is called until no more elements are available.

What is a method-wrapper and what does it do? How is it applied here: in mygen() and __iter__()?

A method wrapper is, if I'm not mistaken, a method implemented in C. Which is what both these iter(list).__iter__ (list is an object implemented in C) and gen.__iter__ (not sure here but generators are probably too) are.

If __next__ is what both generator and iterator provide (and their sole properties) then what is the difference between generator and iterator?

A generator is an iterator, as is the iterator provided from iter(l). It is an iterator since it provides a __next__ method (which, usually, when used in a for loop it is capable of providing values until exhausted).

🌐
Pierian Training
pieriantraining.com › home › understanding the ‘next’ keyword in python
Understanding the 'next' Keyword in Python - Pierian Training
April 28, 2023 - When we call the `next()` function on an iterator object, it returns the next value from the sequence. If there are no more elements, it raises the `StopIteration` exception. It is important to note that once an iterator has reached its end, ...
🌐
Python
wiki.python.org › moin › Iterator.html
Iterator
An iterable object is an object that implements __iter__, which is expected to return an iterator object. An iterator object implements __next__, which is expected to return the next element of the iterable object that returned it, and to raise a StopIteration exception when no more elements ...
🌐
Python Morsels
pythonmorsels.com › next
Python's next() function - Python Morsels
July 17, 2023 - That function manually calls next on iterators corresponding to each of the given iterables, one after the other. If you're curious about that sentinel = object() line, see Unique sentinel values in Python.
🌐
Reddit
reddit.com › r/learnpython › confused with __iter__ and __next__ for python classes?
r/learnpython on Reddit: Confused with __iter__ and __next__ for python classes?
November 12, 2022 -

Working on a assignment and need to use them, but am super confused how? I've tried looking up tutorials but none of it really makes any sense to me .

#Trying to work on a fibbonachi sequence project where the user enters a number (eg 4 =  [0, 1, 1, 2, 3] , 10 =  [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] )

Just kinda confused, since I was told it is used on lists and tuples but I need to return the list so idk how that would work?

Sorry if this is a dumb question, just not sure at all what to do.

Here's everything I managed to come up with so far.

class Fibonacci:
    # Fibonacci class
     def __init__(self,number_list):
         # get number from the user
         self.number_list = number_list
         self.fib_list = []
         self.a = 0
         self.b = 1
         
    def __iter__(self):
        # confused what this is for?
        return self
    
    def __next__(self):
        # get all Fibonacci numbers 
        # eg 5 = first 5 numbers?
       # [num_list for num_list in range(0, number)]
       if len(self.num_list) > 0:
           # swaps fib numbers and adds them to the list?
           self.c = self.a + self.b 
           self.a = self.b 
           self.b = self.c
           self.fib_list.append(self.c)

Thanks :)

🌐
GeeksforGeeks
geeksforgeeks.org › python › python-__iter__-__next__-converting-object-iterator
Converting an object into an iterator - Python
March 10, 2025 - The __next__() function in Python returns the next element of an iteration. If there are no more elements, it raises the StopIteration exception.
Top answer
1 of 2
3

What you're talking about is not really up to the next function, but rather up to how each iterator implements its next method. And, while many iterators do "advance" when you call next, they don't have to.


The prototypical iterator is a virtual "pointer" to a position in some iterable, and their next method returns the value the iterator is currently pointing to, and advances it to point to the next value in the iterable.

For example, consider the iterator returned by calling iter on a list. The first call to next(i) returns element 0, then the next call returns element 1, and so on. You could simulate its behavior like this:

class ListIterator(object):
    def __init__(self, lst):
        self.lst = lst
        self.idx = 0
    def next(self):
        try:
            value = self.lst[self.idx]
        except IndexError:
            raise StopIteration
        self.idx += 1
        return value

And obviously that's intended to be the usual case, hence the name next.


But you can easily create an iterator that doesn't work this way—and not just as some pathological type to prove a point, but actual useful iterators.

For example, look at itertools.repeat. The iterator returned by itertools.repeat(10) just gives you 10 each time you call next on it. You could think of it as an iterator over a list of infinite length whose elements are all 10, but that's obviously not how it really works. It actually works like this:

class RepeatIterator(object):
    def __init__(self, value):
        self.value = value
    def next(self):
        return self.value

Other iterators work by computing values on the fly, pulling buffers off a socket, etc. You can always find a way to think of any iterator as a pointer to a position within some kind of virtual sequence, just like that virtual infinite list of 10s, but it's often a stretch, and in those cases it's more helpful to just think about what's really happening—calling the next method.


By the way, this is a lot easier to talk about in Python 3, where you have a next function that calls a __next__ method, rather than a next method. And of course Python 3's way follows the same pattern as ever other special method—iter(i) calls i.__iter__(), getattr(obj, attr) calls obj.__getattr__(attr), and next(i) calls i.__next__().

2 of 2
1

You seem to be used to iterators from something like C++, where they're generalized pointers. Iterators in Python don't have "dereference" and "advance" operations; they have "get the next thing", where the fact that the "next thing" is the thing after the previous thing that came out of the iterator is implied by the fact that it's the next one.

The documentation could explicitly state that the operation changes the iterator's state. This could be clearer, but there's a tradeoff in word count and repetition of information. If you follow the link to the next method, you can see the full iterator protocol, which notably only has __iter__ and next in it, making it pretty clear that there's no separate operation to advance the iterator. That documentation still doesn't explicitly say that next advances the iterator, though.

🌐
Medium
medium.com › @dinukathathsara › understanding-next-in-python-1e6b29b606fa
Understanding next() in Python. Introduction Imagine a cluttered desk… | by Dinuka Thathsara | Medium
January 14, 2025 - What Is next()? The next() function retrieves the next item from an iterator. If no item is found, it uses a default value to prevent errors.
🌐
Reddit
reddit.com › r/learnpython › why iter() & next()
r/learnpython on Reddit: Why iter() & next()
December 11, 2022 -

I'm following a (nice) formation to python, and I just watched the part on iter(). And I wonder, why use this function instead of

for thing in acontainer:

that seems easy to use and understand ??? Or I missed something about the utility of this function?

Are there "real" use for iter() in "real" programs ?

🌐
W3Schools
w3schools.com › python › python_iterators.asp
Python Iterators
Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__().
🌐
Codecademy
codecademy.com › docs › python › built-in functions › next()
Python | Built-in Functions | next() | Codecademy
July 8, 2025 - In Python, the next() function returns the next element from an iterator object.
🌐
Biome
biomejs.dev
Biome, toolchain of the web
next · More than 500 lint rules with Biome v2.5! Format, lint, and more in a fraction of a second. Get started View on GitHub · Biome is a fast formatter for JavaScript, TypeScript, JSX, TSX, JSON, HTML, CSS and GraphQL that scores 97% compatibility with Prettier (see known limitations), saving CI and developer time.
🌐
Google Cloud
cloud.google.com › blog › topics › google-cloud-next › welcome-to-google-cloud-next26
Welcome to Google Cloud Next26 | Google Cloud Blog
April 22, 2026 - Data Agent Kit delivers a Gemini-powered data science authoring experience across your IDEs, Notebooks, and Agentic Terminals. It enables data practitioners with intent-driven development in Python, Spark, and SQL—simply state your business goal, and the Data Agent Kit handles the rest.