-1

The title is not clear, let me explain.

If I have two elements of equal value in a List and I wanna get the index of the second one, how would I do it?

list = [
        "foo",
        "default",
        "placeholder",
        "foo"         -> this is the one I need
       ]

list.index("foo") returns 0, I need the index of the second "foo" in the List.

  • 2
    Welcome to Stack Overflow! Please take the [tour], and read [ask], [what's on-topic here](/help/on-topic), and the [question checklist](//meta.stackoverflow.com/q/260648/843953). [Asking on Stack Overflow is not a substitute for doing your own research.](//meta.stackoverflow.com/a/261593/843953) – Pranav Hosangadi Apr 06 '21 at 21:24
  • 2
    What have you tried to solve this? For example, in [the docs](https://docs.python.org/3/tutorial/datastructures.html), `index()` takes two optional arguments, `start` and `end`. `start` seems particularly applicable here – G. Anderson Apr 06 '21 at 21:24
  • Does this answer your question? [Finding the index of an item in a list](https://stackoverflow.com/questions/176918/finding-the-index-of-an-item-in-a-list) – Pranav Hosangadi Apr 06 '21 at 21:26
  • Read the docs for `list.index` and see if you find anything useful. – wim Apr 06 '21 at 21:27
  • do `list.index` twice. – Aaron Apr 06 '21 at 21:37

1 Answers1

0

By using enumerate(), we can look for the "foo" that appears beyond the index of its first appearance:

lst = ["foo", "default", "placeholder", "foo"]

item = "foo"

for index, x in enumerate(lst):
  if x == item:
    print(lst.index(item, index))
LWHR
  • 71
  • 4