I thought that the range() function returns a list with the arguments that you have put inside the parentheses. But when I type range(4)
in IDLE, I get range(0, 4)
as output. Similarly, when I type print(range(4))
, I also get range(0, 4)
as output. I am currently using python 3.5.
I am currently studying python with the following eBook: "How To Think Like a Computer Scientist" and in that eBook, they provide active code blocks where you can run python code. And when I run print(range(4))
in there, I do get the list that I expected, i.e. [0, 1, 2, 3]
.
Can someone explain this to me?
Thanks in advance!
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.
Return value The returned value is an integer and represents the total number of values present in a particular range.
The range() is an in-built function in Python. It returns a sequence of numbers starting from zero and increment by 1 by default and stops before the given number. It has three parameters, in which two are optional: start: It's an optional parameter used to define the starting point of the sequence.
Return Value: In the above example, the range(5) returns the range object with the default start 0, stop 5, and default step 1. The range is an immutable sequence, so that values can be accessed by passing indexes in the square brackets [].
print(range(10)) returns range(0, 10) as output
In many ways the object returned by range() behaves as if it is a list, but in fact it isn’t. It is an object which returns the successive items of the desired sequence when you iterate over it, but it doesn’t really make the list, thus saving space.
We say such an object is iterable, that is, suitable as a target for functions and constructs that expect something from which they can obtain successive items until the supply is exhausted. We have seen that the for statement is such an iterator. The function list() is another; it creates lists from iterables:
list(range(5)) returns [0, 1, 2, 3, 4] as output
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