-1

Without using numpy, my question is related to the for loop in Python, as it doesn't have for i=0, i++ ...

only for i in list

I need

for i in list 
  # print(i.index)
  # i.index being 0 at the first element of the list and
  # ordered to len(list)-1 at the last element 

There is something I am missing :

mat=[[1,0,1],
     [1,1,1],
     [1,0,1]]
 
dict1= []
dict2= []
n=len(mat[0])
for row in mat :
    for j in range(n):           
        if row[j]==0: 
            dict1.append(mat.index(row))
            dict2.append(j)
print(dict1)
print(dict2)

output should be [0,2] and [1,1] but instead I am getting

[0,0] 
[0,1]

How do we explain this?

NotaChoice
  • 119
  • 5
  • 1
    Does this answer your question? [Accessing the index in 'for' loops](https://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops) – ssp May 04 '22 at 14:47

3 Answers3

1

Another possibility is for i,v in enumerate(my_list): print(i, v). The i value goes from 0 to len(my_list) - 1. The functionenumerate has keyword argument start that allow to specify where i starts (as above this defaults to 0).

thebadgateway
  • 433
  • 1
  • 4
  • 7
0

Use .index()

l=[1,2,3]
for i in l:
    print(i,l.index(i))

1 0
2 1
3 2
Sruthi
  • 2,908
  • 1
  • 11
  • 25
0

Using .index() is okay, as long as the list does not have double entries, because index returns the index of the first occurrence of an item.

The for loop can iterate over an index i in some range as follows:

l=[1,2,3,5,6,7,3,1,89,2,77]
for i in range(0,len(l)):
    print(l[i], i)
a0poster
  • 65
  • 6