Python | Check for Nth index existence in list (original) (raw)

Last Updated : 24 Mar, 2023

Sometimes, while working with lists, we can have a problem in which we require to insert a particular element at an index. But, before that it is essential to know that particular index is part of list or not. Let’s discuss certain shorthands that can perform this task error free.

Method #1 : Using len() This task can be performed easily by finding the length of list using len(). We can check if the desired index is smaller than length which would prove it’s existence.

Python3

test_list = [ 4 , 5 , 6 , 7 , 10 ]

print ("The original list is : " + str (test_list))

N = 6

res = len (test_list) > = N

print ("Is Nth index available? : " + str (res))

Output :

The original list is : [4, 5, 6, 7, 10] Is Nth index available? : False

Time Complexity : O(n)

Auxiliary Space : O(n), where n is length of list.

Method #2 : Using try-except block + IndexError exception This task can also be solved using the try except block which raises a IndexError exception if we try to access an index not a part of list i.e out of bound.

Python3

test_list = [ 4 , 5 , 6 , 7 , 10 ]

print ("The original list is : " + str (test_list))

N = 6

try :

`` val = test_list[N]

`` res = True

except IndexError:

`` res = False

print ("Is Nth index available? : " + str (res))

Output :

The original list is : [4, 5, 6, 7, 10] Is Nth index available? : False

Time Complexity: O(n*n) where n is the length of the list
Auxiliary Space: O(1), constant extra space is required

Method#3: using the in operator

Python3

test_list = [ 4 , 5 , 6 , 7 , 10 ]

print ( "The original list is : " + str (test_list))

N = 6

res = N in range ( len (test_list))

print ( "Is Nth index available? : " + str (res))

Output

The original list is : [4, 5, 6, 7, 10] Is Nth index available? : False

Time Complexity: O(n)

Auxiliary Space: O(1)

Similar Reads