I find myself frequently writing code like this:
k = 0
for i in mylist:
# y[k] = some function of i
k += 1
Instead, I could do
for k in range(K):
# y[k] = some function of mylist[k]
but that doesn’t seem “pythonic”. (You know… indexing. Ick!) Is there some syntax that allows me to extract both the index (k) and the element (i) simultaneously using either a loop, list comprehension, or generator? The task is in scientific computing, so there is a lot of stuff in the loop body, making a list comprehension probably not powerful enough on its own, I think.
I welcome tips on related concepts, too, that I might not have even though of. Thank you.
You can use
enumerate:More information about looping techniques.
Edit:
As pointed out in the comments, using other variable names like
makes it easier to read and understand your code in the long run. Normally you should use
i,j,kfor numbers and meaningful variable names to describe elements of a list.I.e. if you have e.g. a list of books and iterate over it, then you should name the variable
book.