Dylan Klomparens
Dylan Klomparens

Reputation: 2932

List boundaries - what is the most Pythonic way?

I have a Python list and I want to check if a given index is out of bounds. Since I'm accepting user input I want to restrict the index to integers greater than or equal to 0. What is the most Pythonic way to do this? Currently, this is my solution:

def get_current_setting(self, slot):
    if slot < 0 or slot > len(self.current_settings) - 1:
        raise Exception("Error message...")
    return self.current_settings[slot]

Upvotes: 0

Views: 1478

Answers (3)

tobias_k
tobias_k

Reputation: 82899

In Python, you can do both checks (lower and upper bound) at once, making the if-condition much more readable:

def get_current_setting(self, slot):
    if not 0 <= slot < len(self.current_settings):
        raise Exception("Error message...")
    return self.current_settings[slot]

Upvotes: 1

Emilio M Bumachar
Emilio M Bumachar

Reputation: 2613

I'd replace your if line with this:

  if slot not in range(len(self.my_list)):

Upvotes: 0

Gareth Latty
Gareth Latty

Reputation: 88977

Why not just try and access the value, and you will get an IndexError if it's out of bounds. Any checks you want to do out of the ordinary, just do those beforehand manually.

def get_current_settings(self, slot):
    if slot < 0:
        raise IndexError(...)
    return self.my_list[slot]

Upvotes: 2

Related Questions