How to get the index of a for loop in Python?
To get the index of a for loop in Python, use the enumerate() built-in function. The enumerate() function takes an iterable for example a list or a tuple and returns an enumerated object. The function adds a counter as the key of the enumerated object for each element.
The big advantage of using the enumerate() function is that you don't have to use a manually declared counter.
This makes your code much cleaner and easier to understand.
get index of a for loop
You can get the added counter by specifying it in the for loop as shown below:
# get index of a for loop
myList = [5, 25, 525]
for myId, myValue in enumerate(myList):
print('Item #', myId, ' = ', myValue)
In this example, the list myList is enumerated. It is then specified that both ids and values are iterated through.
For each element the id and value are printed.
Item # 0 = 5
Item # 1 = 25
Item # 2 = 525
get index of a for loop start with 1
To start with an index of 1 instead of 0, use the start parameter of the enumerate() function as shown below.
# get index of a for loop - start index at 1
myList = [5, 25, 525]
for myId, myValue in enumerate(myList, start=1):
print('Item #', myId, ' = ', myValue)
In this example, the start parameter is set to 1.
The enumerate function will start the enumeration at index 1 instead of index 0 - the default value.
Item # 1 = 5
Item # 2 = 25
Item # 3 = 525
enumerate on tuples
The enumerate function works with all iterable objects like lists, tuples and even strings.
To demonstrate this, see the enumerate() function used on a tuple below.
# get index of a tuple
myTuple = ('a', 'b', 'c')
for id, val in enumerate(myTuple):
print(id, val)
The tuple is enumerated and each element is printed as key and value pair.
0 a
1 b
2 c
enumerate on nested tuples
The enumerate() function works on nested tuples as well. Use it as shown below.
# enumerate on nested tuples
myTuple = ('a', 'b', 'c', ('d', 'd'), 'e', 'f')
for id, val in enumerate(myTuple):
print(id, val)
In this example the enumerate() function is used on a nested tuple.
The inside tuple is enumerated as one element with the id 3.
0 a
1 b
2 c
3 ('d', 'd')
4 e
5 f
enumerate on strings
If the enumerate() function is used on strings, each character receives an id. Use the enumerate() function on strings as shown below.
# enumerate function on strings
myString = 'hello world'
for id, val in enumerate(myString):
print(id, val)
Here the enumerate function is used on a string. Each character is enumerate as one id. Spaces are also considered as one character.
0 h
1 e
2 l
3 l
4 o
5
6 w
7 o
8 r
9 l
10 d