Issue
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)
Solution
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
Answered By - DirtyBit
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.