0

I am trying to write a function that checks if values index exists or does not. The function checks if n causes an out of bounds error. How would I be able to check this?

values = ["a", "b", "1"]

def check(n):
    if values[n]:
        print("value exists")
    else:
        print("value doesnt exist")

check(1)
check(4)
check(2)
tony selcuk
  • 709
  • 3
  • 11
  • Does this answer your question? [How can I check if a list index exists?](https://stackoverflow.com/questions/29715501/how-can-i-check-if-a-list-index-exists) – Pranav Hosangadi Jun 04 '21 at 17:34

3 Answers3

1

Use Exception handling

def check(n):
  try:
    print(values[n])
  except IndexError:
    # Index Out of Bound 
    print("value doesnt exist")
Nannigalaxy
  • 492
  • 6
  • 17
0

You don't need to use exception handling and it's better to avoid it.

def check(n):
    if n >= 0 and n < len(values):
        print("value exists")
    else:
        print("value doesnt exist")
Caleb George
  • 234
  • 1
  • 10
  • 1
    In this case, it's better to avoid it since the `len()` check is pretty cheap. It's important to remember that an `if` statement _always_ has a cost, where a `try-except` incurs a cost _only when an error is thrown_. If you expected to do this check _thousands_ of times and fail only once or twice, using exception handling would be a better approach. Both paradigms -- EAFP and LBYL -- are perfectly acceptable when used in the correct way. https://stackoverflow.com/questions/1835756/using-try-vs-if-in-python – Pranav Hosangadi Jun 04 '21 at 17:39
  • Thanks @PranavHosangadi; that is a great point. – Caleb George Jun 04 '21 at 18:44
0

In calling an item in a list, Python takes 1 as the 2nd of the list, and 0 as the 1st of the list, 3 as the 4th of the list, and so on. Translating the next three lines of the code after the function defined, "check list No.2, check list No. 5, check list No. 3". there is no more than 3 items, so check(4) raises the error. Tweak the definition of check(n), something like the one shown below:

values = ["a", "b", "1"]
def check(n):
    try:
        print(values[n], 'exists')
    except:
        print("value doesn\'t exist")

The try keyword just tests if it raises no errors. If it does, it hops on over to except keyword, executing that one. The code above specifies the value item, and the comma would be not belting an error. Try it again, and the output:

b exists
value doesn't exist
1 exists

Be careful though, if you're trying to print out one line of string for one error, don't just type (except:) when it is supposed to be (except name of error:) for every single unique error planned to be in the program. It'll execute only the very first one, and not the rest.

Qihua Huang
  • 34
  • 1
  • 2