Asilver
Asilver

Reputation: 53

Python list index from a certain point onwards

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

Answers (2)

Ajax1234
Ajax1234

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

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

The list.index [doc] function has extra parameters:

list.index(x[, start[, end]])
Return zero-based index in the list of the first item whose value is x. Raises a ValueError if there is no such item.

The optional arguments start and end 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 the start argument.

So you can use:

a.index(2, 2)

to start searching from index 2 (including index 2).

Upvotes: 4

Related Questions