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.
We use the operator in
, which returns a Boolean indicating the existence of the value within the array. This way:
lista = [1, 50, 30]
if 50 in lista: # Imprime lo de abajo
print("El número 50 existe en la lista")
otra_lista = ["perro", "gato", "conejo"]
if "caballo" in otra_lista: #No imprime nada
print("caballo existe dentro de otra_lista")
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.
If we want to obtain the index or position, we use the index
method of the lists. This way:
lista = [1, 50, 30]
indice = lista.index(50)
print("El número 50 está en la posición {} de la lista".format(indice))
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:
otra_lista = ["perro", "gato", "conejo"]
try:
otro_indice = otra_lista.index("caballo")
print("caballo está en la posición {} de otra_lista".format(otro_indice))
except:
print("Lo siento, caballo no está en la lista")
In that case, an exception is generated; because the element does not exist in the list.
In the last months I have been working on a ticket designer to print on…
In this post you will learn how to use the Origin Private File System with…
In this post you will learn how to download a file in the background using…
In this post I will show you how to use SQLite3 directly in the web…
In this tutorial, we'll explore how to effortlessly print receipts, invoices, and tickets on a…
When printing receipts on thermal printers (ESC POS) sometimes it is needed to print images…
Esta web usa cookies.