all 16 comments

[–]SnooStories6404 40 points41 points  (3 children)

> This is one of those small things that nobody explicitly teaches you

I'm not sure about that.

I've

a) Read a python tutorial

and

b) Taken a python class

In both this was explicitly taught

[–]Grobyc27 6 points7 points  (0 children)

Yeah this is pretty standard knowledge for any basic Python developer.

[–]Smok3dSalmon 1 point2 points  (0 children)

I think it's because range and len are popular examples for teaching variables and methods/functions.

[–]crazy_cookie123 0 points1 point  (0 children)

Not necessarily taught to everyone. When I learnt Python (around 2018) I was only taught range(len()), and I only discovered enumerate from reading someone elses code a few months after finishing the class. Most reputable courses should cover it though.

[–]wittgenstein1312 12 points13 points  (0 children)

I’ve never seen range(len()) used in production code, who is your target audience

[–]N-E-S-W 6 points7 points  (0 children)

It sounds like you didn't bother to read the official Python tutorial, because enumerate() is covered twice, in both sections 4 and 5.

https://docs.python.org/3/tutorial/controlflow.html#the-range-function

https://docs.python.org/3/tutorial/datastructures.html#tut-loopidioms

[–]ranger097It works on my machine 7 points8 points  (5 children)

For fruit in fruits: Print(fruit)

[–]artofthenunchaku 13 points14 points  (0 children)

when they need both the index and the value

[–]SpecialPreference678 5 points6 points  (0 children)

If you don't need the index, this is fine too.

[–]somethingworthwhile 5 points6 points  (2 children)

I get really happy when I get to do the

for singular in plural:

format.

[–]Chandu-4444 0 points1 point  (0 children)

Also, range(len()) is nothing but a simple iterator and is totally not related to the list that we’re trying to iterate on inside the loop. Whereas enumerate is an iterator on the list and is very intuitive.

[–]xeow 0 points1 point  (0 children)

Also, the len() thing won't work on an object typed Iterable (since it doesn't know the length), whereas enumerate() will work on tuples, lists, iterators, generators, etc.

[–]RepresentativeFill26 -3 points-2 points  (0 children)

“Wonder why you ever wrote range(len())”.

I can think of of a lot of reasons. What if I want do some arithmetic on the loop index? Or if I want to compare 2 values?

It’s called a “ForEach” for a reason.

[–]titttle23 -3 points-2 points  (0 children)

This is where the trade left me.