Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a <class 'range'>

Python3:

string = range(10)
print("{}".format(type(string)))

The output:

class 'range'

I am just curious about this class 'range'. Could anyone explain?

But in Python2:

The output:

class 'list'

Well, it is self explanatory

like image 243
Vivek Avatar asked Aug 31 '16 06:08

Vivek


2 Answers

In Python 2 range(val) produces an instance of a list, it simply a function. Thereby type(range(10)) will return class 'list'.

In Python 3, range is equivalent to xrange in Python 2 and it returns an instance of a new class named range. For more changes/differences between Python 2/3 see PEP 3100.

like image 171
Dimitris Fasarakis Hilliard Avatar answered Oct 14 '22 14:10

Dimitris Fasarakis Hilliard


Python 3 added a new range class to efficiently handle "an immutable sequence of numbers" (similar to Python 2's xrange). Python 2 does not have such a range class, so the range function just returns a list.

like image 3
Mureinik Avatar answered Oct 14 '22 13:10

Mureinik