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:

pythonlst = ['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:

pythonfor item in enumerate(lst):
  print(item)

After executing the code, tuples from the index and element will be output:

python(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:

pythonfor item in enumerate(lst):
  key, value = item
  print(key)
  print(value)
  print()

Result of code execution:

python0, 'a'

1, 'b'

2, 'c'

In abbreviated form, indices and elements can be rewritten immediately in the for block:

pythonfor key, value in enumerate(lst):
  print(key)
  print(value)
  print()

Practical tasks

Задание 1

Given a list:

pythontst = [8, 6, -4, 2, -1]

Print to the console the values ​​of the elements and their indices up to the first negative number.

Задание 2

Given a list:

pythontst = ['a', 'b', 'c', 'd', 'e']

Output the values ​​of the elements and their indices to the console:

python'a1'
'b2'
'c3'
'd4'
'e5'
Задание 3

Given a list:

pythontst = [1, 2, 3, 4, 5]

Square the elements in even positions and cube the elements in odd positions.