Sometimes we need to know if an element or value is within a list or array in Python.

There may be a need to simply know if it exists, but it is also possible that we need to obtain the position of an element, that is, its index.

Today we will see how to do it in Python, to check if an element exists in array, as well as to obtain the index of a certain value.

Check if the element exists

We use the operator in, which returns a Boolean indicating the existence of the value within the array. This way:

As we can see, it does not matter if our array or list is string or integer type. Of course, they must be primitive data.

Obtain element index

If we want to obtain the index or position, we use the index method of the lists. This way:

When we run it, it prints position 1 (remember that the values in the list start at 0). It is important to remember that an error will be generated if the element does not exist in the list. To handle it, we can do something like this:

In that case, an exception is generated; because the element does not exist in the list.

¿Encontraste lo que buscabas?

Si es así, suscríbete para que estés enterado de mis nuevos posts sobre programación e informática

Estoy interesado en trabajar contigo de manera remota para llevar tu idea a la realidad, formar parte de tu equipo de desarrolladores, ayudarte con tu tarea, dar asesorías y todo lo relacionado con tecnología y programación. Contáctame para más información
No te vayas sin seguirme en Twitter, Facebook y GitHub
Si tienes dudas déjalas en un comentario, pero asegúrate de seguirme antes como agradecimiento (no te cuesta nada y me ayudas mucho)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
%d bloggers like this: