Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the return value of the range() function in python?

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!

like image 204
I. Wewib Avatar asked May 04 '17 07:05

I. Wewib


People also ask

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 returns the number of values in a range?

Return value The returned value is an integer and represents the total number of values present in a particular range.

What is the use of range () function?

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.

What will range 5 return?

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 [].


1 Answers

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

like image 64
vibhanshu kumar Avatar answered Sep 27 '22 22:09

vibhanshu kumar