Iterate list and return PYTHON index

2

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.

array_1=["1","2","3"]
for i in array_1:
    print(i)

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
source

2 answers

0

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

array_1=["A","B","C"]
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
source
1

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

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