30

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.

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
Steve Tjoa
  • 59,122
  • 18
  • 90
  • 101

2 Answers2

62

You can use enumerate:

for k,i in enumerate(mylist):
    #do something with index k
    #do something with element i

More information about looping techniques.

Edit:
As pointed out in the comments, using other variable names like

for i, item in enumerate(mylist):

makes it easier to read and understand your code in the long run. Normally you should use i, j, k for 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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 3
    enumerate also allows you to start the index where you like using the start parameter. That's pretty handy sometimes. http://docs.python.org/library/functions.html#enumerate – jps Jan 15 '10 at 15:44
  • 1
    I may be alone in this, but using `i` as the variable to hold each element of the iterable would throw me off when reading this code. Aren't `i` and `j` pretty standard variable names for indexes in looping code? – Will McCutchen Jan 15 '10 at 15:59
  • 1
    BUT be careful if you just want to loop over some elements of a list, rather than the whole list. the start parameter is the number that will be assigned to the first item pulled, not the index in the original list. If you write for i, item in enumerate(mylist, start=12) then you get each item from the list, with i starting to count from 12. Similarly, if you go only over a slice, but don't set a start, then i starts at 0. Hope this helps someone. – ViennaMike Jan 04 '15 at 21:29
20

enumerate is the answer:

for index, element in enumerate(iterable):
    #work with index and element
SilentGhost
  • 307,395
  • 66
  • 306
  • 293