0

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?

3
  • No, that doesn't make sense. Commented Feb 6, 2020 at 21:19
  • 3
    It's not the worst thing I've ever seen. One thing it does is clearly delineate that there are two things going on; I'd find it very odd to see an index variable also participating in a calculation. The other thing it does is set up v to potentially do something different later, without having to rewrite the whole thing. Commented Feb 6, 2020 at 21:28
  • It would probably make more sense if it wasn't range(4), but something like for 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} Commented Feb 7, 2020 at 9:32

1 Answer 1

1

This is not great design. For starters it would be less efficient to enumerate the range.

The code you provided would produce the same result as this:

d = {}
for i in range(4):
    d[i] = i ** 2

I would recommend trying variations out in the python console. The advantage your code has over this is that it sets up i and v so if you did want to modify either of these in different ways it could make it clear, especially for maths students (I have seen a whole host of unpythonic things which they do)

1
  • 1
    or even just d = {i: i**2 for i in range(4)}. Using an enumerate() would just obfuscate the intention of the loop Commented Feb 6, 2020 at 22:11

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.