Range() example Secion 1.3 An Inroductory example


#1

Author: Umair_learning_Python

The example in the tutorial shows the following:

In [31]: range(8)

Out[31]: [0, 1, 2, 3, 4, 5, 6, 7]

In [32]: doubles = [2 * x for x in range(8)]

In [33]: doubles

Out[33]: [0, 2, 4, 6, 8, 10, 12, 14]

But when I type the same in jupyter notebook I get the following results:

range(8)
range(0, 8)
doubles = [2 * x for x in range(8)]
doubles
[0, 2, 4, 6, 8, 10, 12, 14]

While the final results are the same, the range is displayed as (0, 8) and not
0,1,2,3,4,5,6,7 like in the tutorial. Any idea why this is happening?


#2

Thanks for pointing this out.

It is related to changes introduced in Python when they switched from Python 2 to Python 3. In Python 2 range(0, 8) returned a a list with the elements [0, 1, 2, 3, 4, 5, 6, 7]. In Python 3 they use a new type called range

In Python 3, type(range(10)) returns range

Python 3.5.1 |Anaconda custom (64-bit)| (default, Dec  7 2015, 11:16:01) 
Type "copyright", "credits" or "license" for more information.

IPython 4.1.2 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: type(range(10))
Out[1]: range

In Python 2, type(range(10)) returns list

Python 2.7.11 |Anaconda 4.0.0 (64-bit)| (default, Dec  6 2015, 18:08:32) 
Type "copyright", "credits" or "license" for more information.

IPython 4.1.2 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: type(range(10))
Out[1]: list

You get the same list for doubles though because it is in a list comprehension.


#3

Author: Umair_learning_Python

Great, thanks Chase.
Umair