+ 2

print(range(x)) flaw

print(range(X)) Output : range(0,X) Why ?

16th Jun 2019, 9:37 AM
Vishal Khushalani
Vishal Khushalani - avatar
6 Antworten
+ 7
range(start, stop, step) creates a range object that goes from <start> to <stop-1> in steps of <step>. If you omit <start> and <stop>, Python assumes that <start> is 0 and <step> is 1. So range(5) is exactly the same as range(0, 5) or range(0, 5, 1). I don't see any flaw.
16th Jun 2019, 9:52 AM
Anna
Anna - avatar
+ 2
You can fix it like this: print(list(range(X))) This will make a list out of it, so it won't just output the function
16th Jun 2019, 9:41 AM
Airree
Airree - avatar
+ 2
Yes, I read it works this way but what's the flaw in that ? How it works behind the scenes ?
16th Jun 2019, 9:42 AM
Vishal Khushalani
Vishal Khushalani - avatar
+ 2
It's because in python3 you have to make it a list
16th Jun 2019, 9:48 AM
Airree
Airree - avatar
+ 2
It works using __iter__. I think range isn't a function, but a class. Let try to create it. class range: def __init__(self, start, stop) : self.start = start self.stop = stop self.actual = self.start - 1 def __iter__(self) : return self def __next__(self): self.actual += 1 if self.actual < self.stop: return self.actual else: raise StopIteration() def __repr__(self): return "range(0, X)"
16th Jun 2019, 9:51 AM
Théophile
Théophile - avatar
+ 2
A good explanation is that range really doesn't create a list but it is a lazy promise to produce that values as and when required
16th Jun 2019, 11:58 AM
Saksham Jain
Saksham Jain - avatar