I'm trying to implement the enumerate built-in using iterators. So far it works but for unordered objects, such as sets or dictionaries, I'm not sure if this implementation is considered valid, although it works.
class myEnumerate:
def __init__(self, iterable):
self.iterable = list(iterable)
self.index = -1
def __iter__(self):
return self
def __next__(self):
self.index += 1
if self.index >= len(self.iterable):
raise StopIteration
return self.index, self.iterable.__getitem__(self.index)
if __name__ == '__main__':
for (i, ch) in myEnumerate("Python"):
print(i, ch)
# Output:
# 0 P
# 1 y
# 2 t
# 3 h
# 4 o
# 5 n
for (i, ch) in myEnumerate(set(["a", "b", "c"])):
print(i, ch)
# Output: (order might differ)
# 0 a
# 1 b
# 2 c
What do you guys think?