简体   繁体   中英

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]

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]

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]

我将用以下内容替换您的if行:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM