Iterate list and return PYTHON index


Good, as an example in a list with a cycle for example. And the for variable will return the index of the list in that iteration instead of the element. An example here goes.

for i in array_1:

I know that in that case my print function will devour the element in which you are iterating the for what would be a string. But how would you get me to return the index of that element. Thanks

asked by limg21 30.06.2017 в 03:36

2 answers


A simple and quite optimal way would be to use the enumerate function, modifying a bit your example, it would be like this:

for i, _ in enumerate(array_1):
    print("El valor de array[{0}] es {1}".format(i,array_1[i]))

Another way, it occurs to me, is using range with the array length

for i in range(len(array_1)):
    print("El valor de array[{0}] es {1}".format(i,array_1[i]))

In both cases the output would be:

El valor de array[0] es A
El valor de array[1] es B
El valor de array[2] es C
answered by 30.06.2017 / 03:47

You can declare an accountant before for and increase it in each iteration:

cont = 0
for i in array_1:
    cont = cont + 1
answered by 30.06.2017 в 03:47