TypeError: 'range' object is not an iterator in Python
Hello you guys, I am a newbie in Python and I'm also studying more about Python.
I have some lines of code, I am using range to help create an array list with 10 items and use to next()
method to help get data from this array. Function as below:
# this creates a list of 0 to 10
# integers
array = range(10)
# print the array
print(array)
# use next
print(next(array))
But I get an exception TypeError: 'range' object is not an iterator when I run code above.
range(0, 10)
Traceback (most recent call last):
File "main.py", line 11, in <module>
print(next(array))
TypeError: 'range' object is not an iterator
And I am using python 3.8.2
Anyone can explain it to me? How can I solve it?
Thanks for any response.
- A1
Armin Habibi Sep 21 2021
The
range
is a class of a list of immutable objects. The iteration behavior ofrange
is similar to iteration behavior of list in list and withrange
we can not directly callnext
function. We can call next if we get an iterator usingiter
.# this creates a list of 0 to 10 # integers array = iter(range(10)) # print the array print(array) # use next print(next(array))
#Output
<range_iterator object at 0x7f8f8133f630> 0
- A0
Akhmir Rudmakh Sep 21 2021
You need to research more about range in Python, I noted a litle as below:
range()
is a function which returns range objectsrange
objects are iterable- Calling
iter()
with a range object gets you an iterator - You can call
iter()
on a range object multiple times and get a new iterator each time
Hope it useful for you to understand more about
range
and resolve your issue.
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.