Check array index python

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

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.

Читайте также:  Управление клавиатурой python pygame

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.

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

Источник

Check array index python

Last updated: Feb 22, 2023
Reading time · 5 min

banner

# Table of Contents

# Check if an index exists in a List in Python

To check if an index exists in a list:

  1. Check if the index is less than the list’s length.
  2. If the condition is met, the index exists in the list.
  3. If the index is equal to or greater than the list’s length, it doesn’t exist.
Copied!
my_list = ['bobby', 'hadz', 'com'] index = 2 if index len(my_list): # 👇️ this runs print('The index exists in the list', my_list[index]) else: print('The index does NOT exist in the list') print(2 len(my_list)) # 👉️ True print(3 len(my_list)) # 👉️ False

check if index exists in list

If the specified index is less than the list’s length, then it exists.

If the list has a length of 3 , then there are 3 elements in the list.

If there are 3 elements in the list, the last element has an index of 2 .

Python indexes are zero-based, so the first item in a list has an index of 0 , and the last item has an index of -1 or len(my_list) — 1 .

Since indexes are zero-based, the last item in a list will always have an index of len(my_list) — 1 .

If the index is less than the list’s length, it’s safe to access the list at the specified index.

# Handling the case where the index might be negative

Here is an example that handles the scenario where the index might be negative.

Copied!
my_list = ['bobby', 'hadz', 'com'] index = -30 if -len(my_list) index len(my_list): print('The index exists in the list', my_list[index]) else: # 👇️ this runs print('The index does NOT exist in the list')

handling the case where the index might be negative

The if statement checks if the length of the list is greater than the specified index.

We also check if the negated length of the list is less than or equal to the index.

This is necessary to handle negative indices, e.g. -30 .

If the list has a length of 3 , the largest negative index in the list is -3 .

Negative indices can be used to count backward, e.g. my_list[-1] returns the last item in the list and my_list[-2] returns the second to last item.

Copied!
my_list = ['bobby', 'hadz', 'com'] print(my_list[-1]) # 👉️ com print(my_list[-2]) # 👉️ hadz print(my_list[-3]) # 👉️ bobby

# Check if an index exists in a List using try/except

You can also use a try/except statement to check if an index exists in a list.

Copied!
my_list = ['bobby', 'hadz', 'com'] try: index = 100 print(my_list[index]) print(f'index index> exists in the list') except IndexError: # 👇️ this runs print('The specified index does NOT exist')

check if index exists in list using try except

We try to access index 100 in the try block and if the index doesn’t exist, an IndexError exception is raised and is then handled by the except block.

If the try block completes successfully, the index exists in the list.

If the except block runs, the index doesn’t exist in the list.

You don’t have to worry about handling negative indices when you use this approach because it does that automatically.

# Get a default value on index out of range in Python

To get a default value on index out of range exception:

  1. Access the list at the specified index in a try/except block.
  2. If the list index out of range exception is raised, return a default value.
  3. Otherwise, return the list item at the specified index.
Copied!
def get_item(li, index, default=None): try: return li[index] except IndexError: return default my_list = ['bobby', 'hadz', 'com'] print(get_item(my_list, 1)) # 👉️ hadz print(get_item(my_list, 25)) # 👉️ None print(get_item(my_list, 25, 'default value')) # 👉️ default value print(get_item(my_list, -1)) # 👉️ com print(get_item(my_list, -25)) # 👉️ None print(get_item(my_list, -25, 'default value')) # 👉️ default value

We used a try/except block to return a default value on a ‘list index out of range’ exception.

We access the list at the specified index in the try block and if the index is out of range, an IndexError is raised.

Copied!
my_list = ['bobby', 'hadz', 'com'] # ⛔️ IndexError: list index out of range print(my_list[25])

We handle the IndexError in the except block by returning a default value.

The default value is set to None unless the user provides a third argument in the call to the function.

Copied!
def get_item(li, index, default=None): try: return li[index] except IndexError: return default my_list = ['bobby', 'hadz', 'com'] print(get_item(my_list, 25)) # 👉️ None print(get_item(my_list, 25, 'default value')) # 👉️ default value

The function returns the list item at the specified index if it is in range, otherwise, a default value is returned.

This approach also handles negative indexes.

Copied!
def get_item(li, index, default=None): try: return li[index] except IndexError: return default my_list = ['bobby', 'hadz', 'com'] print(get_item(my_list, -1)) # 👉️ com print(get_item(my_list, -25)) # 👉️ None print(get_item(my_list, -25, 'default value')) # 👉️ default value

Negative indices can be used to count backward, e.g. my_list[-1] returns the last item in the list and my_list[-2] returns the second to last item.

Alternatively, you can check the list’s length.

# Get a default value on index out of range using len()

This is a three-step process:

  1. Check if the provided index is in range.
  2. If the index is in range, access the list item at the specified index.
  3. Otherwise, return a default value.
Copied!
def get_item(li, index, default=None): return li[index] if -len(li) index len(li) else default my_list = ['bobby', 'hadz', 'com'] print(get_item(my_list, 1)) # 👉️ hadz print(get_item(my_list, 25)) # 👉️ None print(get_item(my_list, 25, 'default value')) # 👉️ default value print(get_item(my_list, -1)) # 👉️ com print(get_item(my_list, -25)) # 👉️ None print(get_item(my_list, -25, 'default value')) # 👉️ default value

We used an inline if/else statement to check if the specified index is in range.

The if statement first checks if the negated length of the list is less than or equal to the index.

This is necessary to handle negative indexes, e.g. my_list[-25] .

If the list has a length of 3 , the largest negative index in the list is -3 .

Источник

Python – Check If Index Exists in List

Lists are a very versatile data structure in Python that is used to store an ordered collection. In this tutorial, we will look at how to check if an index exists in a list or not.

Lists are mutable, so you can perform operations like adding elements, removing elements, extending a list, etc. The values in a list are indexed starting from zero and we can use a value’s index in the list to access it.

How to check if an index exists in a list?

check if an index exists in a python list

A Python list uses integer values starting from zero as its index. So, the first element in the list will have index 0 and the last element in the list has an index equal to the length of the list – 1 (one less than the length of the list).

If the index under consideration is less than the length of the list, we can say that the index exists in the list. The following is the syntax –

We use the Python built-in len() function to get the length of a list. Here, we get True if the index exists in the list and False otherwise.

There are other methods as well that you can use to check if an index exists in a list or not. For example –

  • Using try and except blocks. First, try to access the list value at the index under consideration inside a try block and use an except block to catch an IndexError . If the index exists in the list, no errors will be raised. If the index doesn’t exist, an IndexError is raised which will be handled by the except block (see the examples below).

Examples

Let’s look at some examples of using the above methods.

Example 1 – Check if an index exists using the list length

Let’s create a list and check if a valid index exists or not.

# create a list ls = ['milk', 'eggs', 'bread'] i = 2 # check if index i is present in the list print(i < len(ls))

Here, we created a list of length 3 and checked for the index 2. You can see that we get True as the output as the index 2 exists.

Let’s now access an index that does not exist.

# check if index 3 is present in the list print(3 < len(ls))

We get False as the output.

What if the list is empty? Let’s find out.

# create an empty list ls = [] # check if index 0 is present in the list print(0 < len(ls))

Here, we created an empty list and checked if the index 0 is present. We get False as the output.

Example – Check if an index exists using try – except

Alternatively, we can use error handling to check if an index exists in the list or not.

The idea is to try to access the list value at the given index inside a try block, now if the index exists, no errors will be raised but if the index does not exist, an IndexError gets raised which can be handled by an except block.

# create a list ls = ['milk', 'eggs', 'bread'] i = 3 # check if index i is present in the list try: ls[i] print("Index present") except IndexError: print("Index not present")

Here, we tried accessing the element at index 3 in a list with three values. Now, since index 3 does not exist, an IndexError got raised which was then handled by the except block. Thus, you can see the result, “Index does not exist”.

Summary

In this tutorial, we looked at some methods to check if an index exists in a Python list or not. The following are the key takeaways –

  • If the index is less than the length of the list you can say that the index exists in the list.
  • Alternatively, you can use error handling to check if an index exists or not. If an IndexError gets raised on trying to access the value at the given index, you can say that the index does not exist.

You might also be interested in –

  • Python – Check If All Elements in List are False
  • Python – Check if All Elements in List are True
  • Python – Check If All Elements in List are Positive
  • Python – Check If All Elements in List are Strings
  • Python – Check If All Elements in List are Integers
  • Python – Check If All Elements in List are None
  • Python – Check If All Elements in List are Zero
  • Python – Check If All Elements in a List are Equal
  • Python – Check If All Elements in a List are Unique
  • Check If a List Contains Only Numbers in Python
  • Python – Check List Contains All Elements Of Another List
  • Python – Check if an element is in a list
  • Python – Check If List Is Sorted Or Not

Author

Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts

Источник

Оцените статью