Slicing Lists and Tuples in Python

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

Internal

Overview

Slicing means extracting of a section of elements from of a list or a tuple, using the slice notation:

[<start-index>:<end-index>:<step>]

The elements are selected as follows: start with the start index, and keep adding the step value to obtain the indices of the selected elements. Stop when the index value such computed is equal or larger than the end index. In case of a negative step, stop if the index value such calculated is equal or smaller than the end index.

Step

The steps represents the increment added to start index to obtain selected indexes. The elements are selected starting from the start index (inclusive) and then successively adding the step value to obtain the value of the selected indexes, until the index value is equal or larger than the end index.

If the step is omitted, it defaults to 1. [1:3], [1:3:] and [1:3:1] are equivalent and result in:

l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
l[1:3]   # ['b', 'c']
l[1:3:]  # ['b', 'c']
l[1:3:1] # ['b', 'c']

If the step has a value larger than 1, non-successive elements are selected:

l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
l[1:6:2]   # ['b', 'd', 'f']

If the step has a negative value, the same algorithm applies: the interpreter starts with start index, keeps adding the step in a loop, which now is a negative value, so the iteration advances toward the beginning of the list, and stops when the resulted index is equal or smaller than the end index:

l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
#     0    1    2    3    4    5    6    7

l[6:3:-1]    # ['g', 'f', 'e']

Reversing a List using a Slice




A sub-sequence of a list can be extracted with a slice. The slice [<start-index>:<end-index>:<step>] specified the index of the last element, and the index of the first element not included in slice, and the step. The step is optional, the default value is 1.

l = ['a', 'b', 'c', 'd', 'e', 'f']
assert ['a', 'b', 'c', 'd', 'e', 'f'] == l[:] # starts from the beginning and ends after the end of the list
assert ['c', 'd'] == l[2:4]
assert ['c'] == l[2:4:2]

The step can be negative, which means the slice starts at the end and goes from right to left.

l = ['a', 'b', 'c', 'd', 'e', 'f']
assert ['f', 'e', 'd', 'c', 'b', 'a'] == l[::-1]

[:] creates a copy of the list.

l = ['a', 'b', 'c']
l2 = l[:]
l2[0] = 'x'
assert ['a', 'b', 'c'] == l
assert ['x', 'b', 'c'] == l2

Remove the last element of the list:

l = ['a', 'b', 'c']
l2 = l[:-1]
assert ['a', 'b'] == l2

Extract Elements from the Tail of the List Starting with a Certain Index

l = [1, 2, 3]
assert l[0:] == [1, 2, 3]
assert l[1:] == [2, 3]
assert l[2:]== [3]
assert l[3:] == [] # empty list
assert l[4:] == [] # empty list

Extract Elements from the Head of the List Counting from the Tail

TODO