Edit: I want to clarify that I am asking here about situations when the index is explicitly required. I know that for item in items
is better when it is not required. I have a long term habit of thinking of list items as my_list[i]
or arr[i]
. I find seeing the name of the list and the index next to each other very clear and helpful. So my question is really whether there is any advantage in changing the way I think about index and value to fit the way enumerate
works.
As the title says. I have read many answers saying for i in range(len(arr))
is bad, but not heard a good reason as to why this is the case. One argument is that it is "un-Pythonic", but it looks pretty Pythonic superficially, compared to the c-style versions.
Since enumerate
has an additional argument which is sometimes not needed, I'm confused as to the advantage, as increased simplicity doesn't seem guaranteed. I would be like to hear more about why I should avoid for i in range(len(arr))
, or whether it is in fact just down to personal preference.
for item in items:
, or you also (but not only) need the index, in which casefor index, item in enumerate(items):
. – Fosdick