+ 2
Range
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.
6 Réponses
+ 7
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)))
+ 4
Btw: You can 'unpack' a range too.
print(*range(5))
+ 3
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
+ 1
@Theo:
It is only an iterator because you have made it one by using "iter" on it. It is not an iterator by itself.
0
What is the result of this code
nums = list(range(5))
Print (nums[4])