Range | Sololearn: Learn to code for FREE!



Why is that when i create a range (eg) print(range(5)) Without any looping method to call it out It just prints the same text back. I know its not a really important question but its got my head itching.

8/29/2019 12:53:16 AM


6 Answers

New Answer


When you do print(type(range(5))) You'll see that it's of its own type, class range, an iterable object. As for why printing the object results in 'range(0,5)', it's really just how the class was designed to behave when the object is converted to string before being printed. Observe: s = str(range(5)) print(s) In order to print all the numbers out, you have to pass it into a list. print(list(range(5)))


Btw: You can 'unpack' a range too. print(*range(5))


It is due to the fact that range is an object and not a function. Second point, range is an iterator. E.g : r = range(5) print(type(r)) #you'll see class range it = iter(r) print(type(it)) #you'll see class range_iterator https://code.sololearn.com/cAIE9Q5eaxzX/?ref=app


List is neccessary before use.. reffrence👇 https://www.sololearn.com/learn/Python/2434/


@Theo: It is only an iterator because you have made it one by using "iter" on it. It is not an iterator by itself.


What is the result of this code nums = list(range(5)) Print (nums[4])