Python | Check for Nth index existence in list

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Check for Nth index existence in list
# Using len()
  
# initializing list
test_list = [4, 5, 6, 7, 10]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing N 
N = 6
  
# Check for Nth index existence in list
# Using len()
res = len(test_list) >= N
  
# printing result 
print("Is Nth index available? : " + str(res))

chevron_right


Output :



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

 

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Check for Nth index existence in list
# Using try-except block + IndexError exception
  
# initializing list
test_list = [4, 5, 6, 7, 10]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing N 
N = 6
  
# Check for Nth index existence in list
# Using try-except block + IndexError exception
try:
    val = test_list[N]
    res = True
except IndexError:
    res = False  
  
# printing result 
print("Is Nth index available? : " + str(res))

chevron_right


Output :

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.