Getting Elements and Their Indices in Python
It is possible to derive not only elements from an iterable object, but also their indices. For this, the enumerate function is used. In its parameter, we specify the desired iterable object.
Example
Let us have a list lst:
lst = ['a', 'b', 'c']
Let's derive the elements with their indices from it. Let's denote the element-index pair as a variable item, which we will look for in the object passed to the enumerate function:
for item in enumerate(lst):
print(item)
After executing the code, tuples from the index and element will be output:
(0, 'a')
(1, 'b')
(2, 'c')
Example
To get the elements and their indices separately, you can unpack them through two variables key and value:
for item in enumerate(lst):
key, value = item
print(key)
print(value)
print()
Result of code execution:
0, 'a'
1, 'b'
2, 'c'
In abbreviated form, indices and elements can be rewritten immediately in the for block:
for key, value in enumerate(lst):
print(key)
print(value)
print()
Practical tasks
Given a list:
tst = [8, 6, -4, 2, -1]
Print to the console the values of the elements and their indices up to the first negative number.
Given a list:
tst = ['a', 'b', 'c', 'd', 'e']
Output the values of the elements and their indices to the console:
'a1'
'b2'
'c3'
'd4'
'e5'
Given a list:
tst = [1, 2, 3, 4, 5]
Square the elements in even positions and cube the elements in odd positions.