Ask for help with a list operation problem

shortly after using python, I encountered a very awkward problem. There is a list, and I want to compare the pre-value with the latter value. Try using a loop, and then index+1 to get the second value, but will report an index overflow? Solve

Apr.22,2022
The first value of

has no preceding value, and the last value has no latter value. You should exclude these two cases when comparing.


def main():
    tmp_list = [1, 2, 23, 4, 7, 9, 22]
    length = len(tmp_list) - 1
    for x in tmp_list:
        current_index = tmp_list.index(x)
        if tmp_list.index(x) == length:
            return
        else:
            print(x, tmp_list[current_index + 1])


if __name__ == '__main__':
    main()
Menu