Home > Blockchain >  How do I check if an item exists without getting "IndexError: list index out of range"?
How do I check if an item exists without getting "IndexError: list index out of range"?

Time:10-12

Let's suppose I have this list:

common_list = ['Potato', 'Tomato', 'Carrot']

I want to check if common_list[3] exists; if it doesn't, I want to add something to it. Here's what I tried:

if common_list[2] and not common_list[3]:
    common_list.insert(3, 'Lemon')

But it gives me the error:

IndexError: list index out of range

CodePudding user response:

It depends exactly what kind of check you want to perform. Here are some possibilities.

Check there are exactly three items:

if len(common_list) == 3:
    common_list.append('Lemon')

Check there are less than four items:

if len(common_list) < 4:
    common_list.append('Lemon')

Check there's no fourth item, or that the fourth item is present but set to None:

if len(common_list) < 4 or common_list[4] is None:
    common_list.append('Lemon')

Check that the list doesn't already contain 'Lemon':

if 'Lemon' not in common_list:
    common_list.append('Lemon')

Don't trigger and catch exceptions when you can avoid them with a simple if check. It's bad style. Exceptions are expensive and catching them is slow. Try to only use them for truly exceptional circumstances where you'd be surprised if an error actually occurred.

CodePudding user response:

Maybe you will try try exception method?

common_list = ['Potato', 'Tomato', 'Carrot']
try:
    common_list[3]
except IndexError:
    common_list.insert(3, 'Lemon')
  • Related