TypeError: 'range' object is not an iterator in Python

Dung Do Tien Sep 21 2021 8

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.

Have 2 answer(s) found.
  • A

    Armin Habibi Sep 21 2021

    The range is a class of a list of immutable objects. The iteration behavior of range is similar to iteration behavior of list in list and with range we can not directly call next function. We can call next if we get an iterator using iter.

     # 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 
  • A

    Akhmir Rudmakh Sep 21 2021

    You need to research more about range in Python, I noted a litle as below:

    1. range() is a function which returns range objects
    2. range objects are iterable
    3. Calling iter() with a range object gets you an iterator
    4. 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.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close