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))
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.
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.
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.
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.
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.
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
>>>
>>> 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With