The fastest way to access indexes of list within loop in Python is to use the enumerate method for small, medium and huge lists. The enumerate() function to generate the index along with the elements of the sequence you are looping over:


values = [100, 200, 300, 400, 500]
for idx, val in enumerate(values):
    print(idx, val)
output

0 100
1 200
2 300
3 400
4 500

enumerate()

enumerate() is a built-in Python function which is very useful when you want to access both the values and the indices of a list.


How to Access Index in Python's for Loop - Stack Abuse

Notes:

  1. Python indexes start at zero.
  2. To get these indexes from an iterable as you iterate over it, use the enumerate function.
  3. Using enumerate in the idiomatic way creates code that is more readable and maintainable.

Also, note that Python's indexes start at zero, so you would get 0 to 4 with the above. If you want the count, 1 to 5, do this:


values = [100, 200, 300, 400, 500]
count = 0 # in case items is empty and you need it after the loop
for count, item in enumerate(values, start=1):
    print(count, item)
output

1 100
2 200
3 300
4 400
5 500
Prev
Index Page
Next
©Net-informations.com