[Python] How to make Python refuse negative index values?

Discussão em 'Python' iniciado por Stack, Junho 28, 2025.

  1. Stack

    Stack Membro Participativo

    Basically I was working on a script where I want to get neighbouring values from a 2D list. I was basically implementing a simple version, where I take the index and add and subtract just one in all directions and catch any out of range indexing with a try except.

    try:
    keys.append(keyboard[index[0]][index[1]-1])
    except IndexError:
    pass
    try:
    keys.append(keyboard[index[0]][index[1]+1])
    except IndexError:
    pass
    try:
    keys.append(keyboard[index[0]-1][index[1]-1])
    keys.append(keyboard[index[0]-1][index[1]])
    keys.append(keyboard[index[0]-1][index[1]+1])
    except IndexError:
    pass
    try:
    keys.append(keyboard[index[0]+1][index[1]-1])
    keys.append(keyboard[index[0]+1][index[1]])
    keys.append(keyboard[index[0]+1][index[1]+1])
    except IndexError:
    pass


    But then of course, when I ran this I wasn't catching exceptions when subtracting 1 from 0, I was just indexing the last element of the list instead.

    I could test for 0 values, but then that means I'm using 2 different tests to determine what's a valid index, and using if statements all the way then I feel it would be messier than this (as I'd have to do nesting in that case). Plus I feel that if I knew of a way to do this it may be valuable in future cases where I intend to only ever use positive values.

    Is there a method or way of indexing from a list to force python to refuse negative numbers and only take positive values?

    Continue reading...

Compartilhe esta Página