0
why the function below "print(list(vague_list))" generates a list consisting of 4 up to 6 elements each being randomly chosen fr
Hi all, Please kindly help to understand why the function below "print(list(vague_list))" generates a list consisting of 4 up to 6 elements each being randomly chosen from the initial list ["A", "B", "C", "D", "E"]? quote import random class VagueList: def __init__(self, cont): self.cont = cont def __getitem__(self, index): return self.cont[index + random.randint(-1, 1)] def __len__(self): return random.randint(0, len(self.cont)*2) vague_list = VagueList(["A", "B", "C", "D", "E"]) print(list(vague_list)) unquote Possible outputs: ['E', 'C', 'C', 'D'], or ['E', 'C', 'C', 'D', 'E'], or ['E', 'C', 'C', 'D', 'E', 'E'], etc. Why and how it works?
1 ответ
+ 2
Hi,
print(list(vague_list)) is equal to print VagueList[0] to VagueList[4] by call to function __getitem__(index)
So, a random value (-1, 0 or 1) is added to index (0 to 4)
While (index + random.randint(-1, 1)) <5, __getitem__ is called
Sometimes, returns 4 values, when random = 1
...
I hope that explain is good for you
Mbzh31