The Python "TypeError: 'list' object is not an iterator" occurs when we try to use a list as an iterator. To solve the error, pass the list to the iter()
function to get an iterator, e.g. my_iterator = iter(my_list)
.
Here is an example of how the error occurs.
my_list = ['a', 'b', 'c']
# ⛔️ TypeError: 'list' object is not an iterator
print(next(my_list))
We tried to use the list as an iterator, but lists are not iterators (they are iterable).
To solve the error, pass the list to the iter() function to get an iterator.
my_list = ['a', 'b', 'c']
my_iterator = iter(my_list)
print(next(my_iterator)) # ️ "a"
print(next(my_iterator)) # ️ "b"
print(next(my_iterator)) # ️ "c"
The iter() function returns an iterator.
An iterator object represents a stream of data. Every time we pass the iterator to the next() function, the next item in the stream is returned.
When the iterator is exhausted, the StopIteration exception is raised.
my_list = ['a', 'b', 'c']
my_iterator = iter(my_list)
try:
print(next(my_iterator)) # ️ "a"
print(next(my_iterator)) # ️ "b"
print(next(my_iterator)) # ️ "c"
print(next(my_iterator))
except StopIteration:
# ️ this runs
print('iterator is exhausted')
When you use a list in a for loop an iterator is create for you automatically.
my_list = ['a', 'b', 'c']
for el in my_list:
print(el) # ️ a, b, c
Iterators are required to have an iter() method that returns the iterator object itself.
Every iterator is also an iterable, however not every iterable is an iterator.
Examples of iterables include all sequence types (list, str, tuple) and some non-sequence types like dict, file objects and other objects that define an iter() or a getitem() method.
When an iterable is passed as an argument to the iter() function, it returns an iterator.
However, it is usually not necessary to use the iter() function because a for statement automatically does that for us.
When you use a for statement or pass an iterable to the iter() function, a new iterator is created each time.
On the other hand, you can only iterate over an iterator once before it is exhausted and appears as an empty container.
If you need to check if a value is iterable, use a try/except statement.
The iter() function raises a TypeError if the passed in value doesn't support the iter() method or the sequence protocol (the getitem() method).
If we pass a non-iterable object like an integer to the iter() function, the except block is run.
my_str = 'hello'
# my_str = 1 # raise exception
try:
my_iterator = iter(my_str)
for i in my_iterator:
print(i) # ️ h, e, l, l, o
except TypeError as te:
print(te)
The iter() function raises a TypeError if the passed in value doesn't support the iter() method or the sequence protocol (the getitem() method).
If we pass a non-iterable object like an integer to the iter() function, the except block is run.
ref: https://bobbyhadz.com/blog/python-typeerror-list-object-is-not-an-iterator