python_sequence_operation_notes

Python Sequence Operation Notes

Sequence Operation Notes

Examples and notes on selected sequence operations in Table 3 and Table 4:

Indexing: S[i]

Fetches components at offsets (first item is at offset 0).

Negative indexes count backward from the end (last item is at offset −1).

S[0] fetches the first item; S[1] fetches the second item.

S[−2] fetches the second-to-last item (same as S[len(S) − 2]).

Slicing: S[i:j]

Extracts contiguous sections of a sequence, from i through j−1.

Slice boundaries i and j default to 0 and sequence length len(S).

S[1:3] fetches from offsets 1 up to, but not including, 3.

S[1:] fetches from offsets 1 through the end (len(S)-1).

S[:−1] fetches from offsets 0 up to, but not including, the last item.

S[:] makes a top-level (shallow) copy of sequence object S.

Extended slicing: S[i:j:k]

The third item k is a stride (default 1), added to the offset of each item extracted.

S[::2] is every other item in entire sequence S.

S[::−1] is sequence S reversed.

S[4:1:−1] fetches from offsets 4 up to, but not including, 1, reversed.

Slice assignment: S[i:j:k] = I

Slice assignment is similar to deleting and then inserting where deleted.

Iterables assigned to basic slices S[i:j] need not match in size.

Iterables assigned to extended slices S[i:j:k] must match in size.

Other

Concatenation, repetition, and slicing return new objects (though not always for tuples).

python_sequence_operation_notes.txt · Last modified: 2024/04/28 03:21 by 127.0.0.1