Tell me why the slice is reset when I take a negative index. And is it possible to bypass the restriction? I tried instead of taking the slice to take the numbers on the index and run iteration - also fails.

c = [1, 2, 3, 4, 5] x = [c[z-2:z+3] for z in range(len(c))] print(x) 

it turns out:

 [[], [], [1, 2, 3, 4, 5], [2, 3, 4, 5], [3, 4, 5]] 

I would like to:

 [[1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5], [3, 4, 5]] 

    2 answers 2

    Negative indices are considered indices from the end of the list.

      0 1 2 3 4 <----- Полоажительные индексы +------+------+------+------+------+ Список ------> | | | | | | +------+------+------+------+------+ -5 -4 -3 -2 -1 <----- Отрицательные индексы 

    For example, for your list c and for z == 0 will be c[z-2:z+3] == c[-2:3] == c[3:3] == [] , because the index is -2 ( the second element from the end of the 5-element list is its third element (counting from zero).

    Negative indices should be disabled:

     x = [c[z-2:z+3] if z - 2 >= 0 else c[0: z+3] for z in range(len(c))] print(x) 

    Conclusion:

     [[1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5], [3, 4, 5]] 
    • Thanks for the help, c [z-2: z + 3] == c [-2: 3] == c [3: 3] == [] - everything is correct, but does not reset it for this reason, if you take a list of 10 elements, we get c [z-2: z + 3] == c [-2: 3] == c [3: 8], and the answer is: [[], [] ... - Pavel ZZZ
    • In the list with 10 elements, index -2 will correspond to index 8 , not 3, so at the end get c [8: 8] , not c [3: 8]. - MarianD 9:21 pm

    If the index is negative, the element is taken from the end of the set. -1 will be equal to the last element, -2 to the last but one and so on.