+ 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.

29th Aug 2019, 12:53 AM
PHILIP
5 Respostas
+ 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)))
29th Aug 2019, 1:46 AM
Hatsy Rei
Hatsy Rei - avatar
+ 4
Btw: You can 'unpack' a range too. print(*range(5))
29th Aug 2019, 8:30 AM
HonFu
HonFu - avatar
+ 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
29th Aug 2019, 7:28 AM
Théophile
Théophile - avatar
+ 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.
29th Aug 2019, 2:24 PM
Thoq!
Thoq! - avatar
0
What is the result of this code nums = list(range(5)) Print (nums[4])
29th Aug 2020, 8:57 PM
Anthony Friday Attai
Anthony Friday Attai - avatar