How to explain the reverse of a sequence by slice notation a[::-1]

前端 未结 7 1214
深忆病人
深忆病人 2020-11-27 22:12

From the python.org tutorial

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size

7条回答
  •  孤街浪徒
    2020-11-27 22:34

    For Python slicing for a sequence[start:stop:step], have derived these rules:

    1. start:stop = start:stop:1
    2. start:stop:(+ or -) step - It means when traversing skip N items in the sequence. However, (-) indicates backward traversal
    3. Remember, position of last item in sequence is -1, and the one before than is -2, and so on..

    # start:stop: +step Rules

    1. Always traverse in forward
    2. Always start from beginning of sequence as its a positive step ( forward )
    3. Start at requested position, stop at requested position but exclude the item stop position
    4. Default start: If start is not provided, start at 0
    5. Default stop: if stop is not provided, it means until the end of the sequence including the last value
    6. If item at stop position is not reachable (item is beyond the end of sequence traversal), slice does not return anything

    # start:stop:-step Rules

    1. Always traverse in reverse
    2. If start position is provided, start from there, but traverse in reverse ( its a step back )
    3. If stop is provided, stop traversing there but exclude this
    4. Default start: If start position is not provided, start position is the last position of the sequence ( since negative traversal)
    5. Default stop: If stop is not provided, it is the beginning of the list ( position 0)
    6. If item at stop position is not reachable (item is beyond the end of sequence traversal), slice does not return anything

提交回复
热议问题