Python

Python: check if item or value exists in list or array

Introduction

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:

See the gist on github.

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:

See the gist on github.

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:

See the gist on github.

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


I am available for hiring if you need help! I can help you with your project or homework feel free to contact me.
If you liked the post, show your appreciation by sharing it, or making a donation

parzibyte

Freelancer programmer ready to work with you. Web, mobile and desktop applications. PHP, Java, Go, Python, JavaScript, Kotlin and more :) https://parzibyte.me/

Entradas recientes

Receipt designer for thermal printers – Free and open source

In the last months I have been working on a ticket designer to print on…

4 months hace

JavaScript: store and read files with the Origin Private File System

In this post you will learn how to use the Origin Private File System with…

7 months hace

JavaScript: download file with fetch

In this post you will learn how to download a file in the background using…

7 months hace

SQLite3 with vanilla JavaScript and OPFS – Hello world

In this post I will show you how to use SQLite3 directly in the web…

9 months hace

Python Thermal Printing: A Comprehensive Guide for Printing on Thermal Printers

In this tutorial, we'll explore how to effortlessly print receipts, invoices, and tickets on a…

10 months hace

Image printing on Thermal printer

When printing receipts on thermal printers (ESC POS) sometimes it is needed to print images…

10 months hace

Esta web usa cookies.