Skip to content

Instantly share code, notes, and snippets.

@lablnet
Last active October 23, 2020 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lablnet/5801812f2149b4cc1c6e2ea2361c4dff to your computer and use it in GitHub Desktop.
Save lablnet/5801812f2149b4cc1c6e2ea2361c4dff to your computer and use it in GitHub Desktop.
Replicate of python range class in Python Class `Range` to understand how it works under the hood.
class Range:
def __init__(self, start, stop=None, step=1):
if step == 0:
raise ValueError("Step can not be zero.")
if stop is None:
start, stop = 0, start
# calculate the effective length once
self.length = max(0, ((stop - start) + (step - 1)) // step)
self.start = start
self.step = step
self.stop = stop
def __str__(self):
return "Range(" + str(self.start) + ", " + str(self.stop) + ", " + str(self.step) + ")"
def __len__(self):
return self.length
def __getitem__(self, item):
if item < 0:
item += len(self)
if item >= self.length:
raise IndexError("Range object index out of range")
return self.start + item * self.step
if __name__ == "__main__":
r = range(8, 140, 5)
R = Range(8, 140, 5)
print(list(r))
print(list(R))
print(len(r))
print(len(R))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment