Why does this code create a backwards version of any list?

for i in list[::-1]:
  ...

The third parameter is called stride. It is optional and defaults to 1 when not specified. It specifies the amount to increment by.

Example

for i in range(0, 10, 2):
    print(i)

0
2
4
6
8

for i in range(10, 0, -2):
    print(i)

10
8
6
4
2

In your example you use it with a list slice, the same principle applies.

3 Likes

Ohh… Is there a reason why the start and end parameters are omitted?

That’s shorthand for saying you want the entire list. You could input the endpoints explicitly too.

2 Likes

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.