What would be the equivalent of find for lists in python?

Asked

Viewed 904 times

4

What would be the equivalent of find used in strings to use in lists? For example, if it is a=['a','b','c'], as return to position 1 of 'b'?

  • 1

    What do you want to do? Find out if there is a value in the list or search for which index the value is in?

  • if this I know but I want to know in which Input this. With the same purpose of find that is used for string

1 answer

5


The method find, of string, returns the smallest index where the searched value is found. In lists, there is the method index:

>>> numeros = [1, 2, 3, 4, 5]
>>> numeros.index(3)
2

I mean, doing numeros.index(3) return the index where the number 3 is - remembering that the index starts at 0, so the third value will be at index 2.

If the value is not found, an exception ValueError will be launched.

>>> numeros = [1, 2, 3, 4, 5]
>>> numeros.index(9)
Traceback (most recent call last):
  File "python", line 1, in <module>
ValueError: 9 is not in list
  • Thank you Anderson, and sorry for the elementary question.

  • 1

    @Brenofaria No need to apologize. Any doubt is valid.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.