Reputation: 53
For a list
a= [1,2,5,3,7,2,3,1,7,4,2,3,4,2,1]
i know that if i do this
a.index(2)
1
However I want want to know what is the cleanest way to find a number from a certain point.
a.index(2,from point 2)
5
Upvotes: 0
Views: 1762
Reputation: 71451
via implementation of list.index
, you can pass your "point" to achieve your desired output:
a= [1,2,5,3,7,2,3,1,7,4,2,3,4,2,1]
print(a.index(2, 2))
Output:
5
However, another possible solution is to built a dictionary:
val = 2
a= [1,2,5,3,7,2,3,1,7,4,2,3,4,2,1]
locations = dict(enumerate([i for i, c in enumerate(a) if c == val], start=1))
print(locations.get(2, False))
Output:
5
Upvotes: 2
Reputation: 476574
The list.index
[doc] function has extra parameters:
Return zero-based index in the list of the first item whose value islist.index(x[, start[, end]])
x
. Raises aValueError
if there is no such item.
The optional argumentsstart
andend
are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than thestart
argument.
So you can use:
a.index(2, 2)
to start searching from index 2 (including index 2).
Upvotes: 4