Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function range() in Python language does not give the expected result

Tags:

python

As a beginner in python, I was trying to test the function range() in the IDLE terminal. I wrote in the terminal the below posted code and I expected to see result like this:

range(10)==>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

But unfortunately, i do not get the expected result

Python Code I Tried:

range(10)
print(range(10))

The Result From The shell:

>>>
print(range(10))
like image 231
Amr Bakri Avatar asked May 07 '13 11:05

Amr Bakri


People also ask

What does range () do in Python?

Python range() Function The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.

Is range () supported in Python?

The range() function is a built-in-function used in python, it is used to generate a sequence of numbers. If the user wants to generate a sequence of numbers given the starting and the ending values then they can give these values as parameters of the range() function.

Does range () return a list?

The range() function, on the other hand, returns a list or sequence of numbers and consumes more memory than xrange() . Since the range() function only stores the start, stop, and step values, it consumes less amount of memory irrespective of the range it represents when compared to a list or tuple.

What is purpose of range () function?

The range() function is a built-in function of Python. It is used to create a list containing a sequence of integers from the given start value to stop value (excluding stop value). This is often used in for loop for generating the sequence of numbers.


2 Answers

In python 3, range() returns a generator, that's why it shows you the object rather than the values:

>>> print(range(10))
range(0, 10)

If you were expecting a list, you will need to convert it to one before printing it:

>>> print(list(range(10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Generators only create one value at a time in order to save memory. You can read up on them here, which includes an example suited to your test case.

like image 92
Gareth Webber Avatar answered Oct 01 '22 01:10

Gareth Webber



Cross version solution

C:\Documents and Settings\U009071\Desktop>python
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> print(list(range(10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
>>> for i in range(10):
...     print(i)
...
0
1
2
3
4
5
6
7
8
9
>>>

Python2:

>>> print(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a = range(10)
>>> print(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Don't know your Python version, but mine works fine. Try specifying range(0,10) to be sure.

like image 30
Torxed Avatar answered Oct 01 '22 01:10

Torxed