Sorry for the weird title but I couldn't think of a better way to explain it. I saw someone do this once and didn't think it was a good idea but I wanted to check. Basically, he wanted to return the numbers 0-3 and do two different things with them. Say he wanted to use one as a key to a dictionary and the other in a value calculation, like this:
d{0:0, 1:1, 2:4, 3:9}
So he did this to return the index twice:
d = {}
for i, v in enumerate(range(4)):
d[i] = v**2
Is that better than writing d[i] = i**2
? I thought it was weird to enumerate range(4)
. I know this might be somewhat subjective but is this bad design or just a preference thing? What's the best practice?
v
to potentially do something different later, without having to rewrite the whole thing.range(4)
, but something likefor i, v in enumerate(range(4, 8))
. But I guess python programmers would prefer a dictionary comprehension, rather then the for loop:d = {i: v**2 for i, v in enumerate(range(4, 8))}
results in{0: 16, 1: 25, 2: 36, 3: 49}