-2

I find myself in the need of counting through lists with the help of for loops. What I end up doing is this:

L = ['A','B','C','D']

n = 0
for i in L:
    print(L[n])
    n += 1

I was wondering if there is a better way for doing this, without having to declare an extra variable n every time?

Please keep in mind that this is just a simplified example. A solution like this would not suffice (although in this example the results are the same):

L = ['A','B','C','D']

for i in L:
    print(i)
Artur Müller Romanov
  • 1,276
  • 2
  • 19
  • 46

2 Answers2

5

Use enumerate:

L = ['A','B','C','D']
for i, x in enumerate(L):
  print(i,x)
Ocaso Protal
  • 17,084
  • 8
  • 69
  • 74
5

From the docs:

In Python, the enumerate() function is used to iterate through a list while keeping track of the list items' indices.

Using enumerate():

L = ['A','B','C','D']

for index, element in enumerate(L):
      print("{} : {}".format(index,element))    # print(index, L[index])

OUTPUT:

0 : A
1 : B
2 : C
3 : D
DirtyBit
  • 15,671
  • 4
  • 26
  • 53