Detailed explanation of [::-1] in python

for value in range(5)[::-1]

    print(value)#It will output 4 3 2 1 0

Detailed explanation:

a=[1,2,3,4,5,6,7,8,9]

b=a[i:j] means copy a[i] to a[j-1] to generate a new list

For example b=a[1:4], then b=[2,3,4]

When i defaults, it starts from 0 by default, eg:b=a[:4], which is equivalent to b=a[0:4], at this time b=[1,2,3,4]

When j defaults to len(arrlist), eg:b=a[1:], just like b=a[1:9], at this time b=[2,3,4,5,6, 7,8,9]

When i and j are both default, it is equivalent to directly copying a copy of a, eg:b=a[:], which is equivalent to b=a[0:9], at this time b=[1,2,3,4 ,5,6,7,8,9]

For the format b=a[i:j:s], i and j have the same meaning as above, and s represents the step size, which is 1 by default

So for the definition of b=a[i:j:1], it is actually the same as b=a[i:j]

When s<0, i defaults to -1, representing the last element of the list, j defaults to -len(arrlist)-1, eg:b=a[::-1] is equivalent to b= a[-1:-len(a)-1:-1], which is to copy from the last element to the first element

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325847019&siteId=291194637