Fix AttributeError: 'generator' Object Has No Attribute 'next' in Python

Fix AttributeError: 'generator' Object Has No Attribute 'next' in Python

Attributes are values related to an object or a class. The AttributeError is raised in Python when you call an attribute of an object whose type is not supported by the method.

For example, using the split() method on an int object returns an AttributeError because int objects do not support the split() method.

In Python 3, there is no .next method attached to the iterator. As a result, you will get an AttributeError when you try to use the .next method on the generator object.

This tutorial will teach you to fix the AttributeError: 'generator' object has no attribute 'next' in Python.

Fix the AttributeError: 'generator' object has no attribute 'next' Error in Python

Here is an example of AttributeError while using the yield statement in Python 3.

def get_data(n):
    for i in range(n):
        yield i
a = get_data(20)
for i in range(10):
    print(a.next())

Output:

Traceback (most recent call last):
  File "c:\Users\rhntm\myscript.py", line 6, in <module>
    print(a.next())
AttributeError: 'generator' object has no attribute 'next'

As you can see, there is an AttributeError in line 6 containing the code print(seq.next()). It is because we have used the .next method to get the next item from the iterator.

The .next method is replaced by the built-in function next() in Python 3. You can fix this error using the next function, as shown below.

def get_data(n):
    for i in range(n):
        yield i
a = get_data(20)
for i in range(10):
    print(next(a))

Output:

0
1
2
3
4
5
6
7
8
9

In Python 2, you can use the .next method, but Python 3 throws an exception, AttributeError.

Now you know how to solve the error 'generator' object has no attribute 'next' in Python. We hope you find this solution helpful.

Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

Related Article - Python Error

  • Python PermissionError: [WinError 5] Access Is Denied
  • Python TypeError: 'DataFrame' Object Is Not Callable
  • Python TypeError: Can't Convert 'List' Object to STR
  • Local Variable Referenced Before Assignment Error in Python
  • Python Handling Socket.Error: [Errno 104] Connection Reset by Peer
  • Python Is Not Recognized in Windows 10