How to get list index and element simultaneously in Python? [duplicate]

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.

Leave a Comment

tech