Home > Enterprise >  Accessing the index or a row in a matrix/ list of lists
Accessing the index or a row in a matrix/ list of lists

Time:05-05

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 

CodePudding user response:

Use .index()

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

1 0
2 1
3 2

CodePudding user response:

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).

CodePudding user response:

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)
  • Related