Change language

Python | range () does not return an iterator

# Python program to understand the range
# this creates a list from 0 to 5
# integers

 

demo = range ( 6 )

 
# print demo

print (demo)

 
# will generate an error

print ( next (demo))

OUTPUT:

 range (0, 6) 

Runtime errors:

 Traceback (most recent call last): File "/home/6881218331a293819d2a4c16029084f9.py", line 13, in print (next (demo)) TypeError: list object is not an iterator 

Note: the above runtime error clearly indicates that the Python range is not an iterator.

Since the range is iterative so we can get an iterator with it, but we cannot directly call next in the following. The example below explains it clearly

# Python range comprehension program

 
# creates an iterator

demo = iter ( range ( 6 ))

  
# print the iterator

print (demo)

 
# use the following

print ( next (demo))

OUTPUT:

 "listiterator object at 0x7f3f32a46450" 0 

The range does not generate all the numbers it contains when we create it. It only gives the numbers that we get using the loop. Range has the following properties.

  • Range objects are immutable, which means they cannot be changed again, so they can be used as an index in dictionaries.
  • They have there are start and end arguments.
  • the same range can be visited over and over

example

# Python range comprehension program

 
# creates a demo range

demo = range ( 1 , 31 , 2 )

  # print range

print (demo)

 
# print start of range

print (demo.start)

 
# range printing step

print (demo. step)

 
# display the index of element 23

print (demo.index ( 23 ))

 
# since 30 no this will give an error

print (demo.index ( 30 ))

OUTPUT:

 range (1, 31, 2) 1 2 11 

Runtime error: because element 30 is missing, an error occurs

 Traceback (most recent call last): File "/home/cddaae6552d1d9288d7c5ab503c54642.py", line 19, in print (demo.index (30)) ValueError: 30 is not in range 

Shop

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Best laptop for engineering student

$

Best laptop for development

$

Best laptop for Cricut Maker

$

Best laptop for hacking

$890

Best laptop for Machine Learning

$950

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method