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.
Armin Habibi Sep 21 2021
rangeis a class of a list of immutable objects. The iteration behavior of
rangeis similar to iteration behavior of list in list and with
rangewe can not directly call
nextfunction. We can call next if we get an iterator using
# this creates a list of 0 to 10 # integers array = iter(range(10)) # print the array print(array) # use next print(next(array))
<range_iterator object at 0x7f8f8133f630> 0
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 objects
rangeobjects are iterable
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
rangeand resolve your issue.