Monday, August 17, 2009

Two ways to get the index and the value from List in Python

There are two ways to get both the index and the value from the List.
One is :
    for index, item in enumerate(L):
print index, item
The other is:
    for index in range(len(L)):
print index, L[index]

Still need to work hard on research. Seems the proof is wrong.


The index method does a linear search, and stops at the first matching item. If no matching item is found, it raises a ValueError exception.

try:
i = L.index(value)
except
ValueError:
i = -1 # no match

To get the index for all matching items, you can use a loop, and pass in a start index:

i = -1
try:
while 1:
i = L.index(value, i+1)
print
"match at", i
except ValueError:
pass

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.