Skip to content

library/stdtypes.html - Mutable Sequence Types - Operations Table - Slice Assignments #119003

Closed
@GavinAnderberg

Description

@GavinAnderberg

Documentation

The table of operations for mutable sequence types has footnote (1) for the operation s[i:j:k] = t, which states that "t must have the same length as the slice it is replacing." When the step size of the slice (k) is 1, the slice object behaves the same as the operation s[i:j] = t. When creating slices with similar values, these slices are distinct:

slice1 = slice(1,10)
slice2 = slice(1,10,1)
slice1 == slice2
#False

But when these slices are used in mutable sequence assignment, they behave the same:

list1 = list(range(10))
print(list1, len(list1))
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 10
list1[slice1] = [None] * 6 #s[i:j] = t | slice of _s_ from _i_ to _j_ is replaced by the contents of the iterable _t_
print(list1, len(list1))
#[0, None, None, None, None, None, None, 6, 7, 8, 9] 11
#Length of list increases by 1 (10 -> 11)

list2 = list(range(10))
list2[slice2] = [None] * 6 #s[i:j:k] = t | the elements of s[i:j:k] are replaced by those of _t_
print(list2, len(list2))
#[0, None, None, None, None, None, None, 6, 7, 8, 9] 11
#Length of list increases by 1 (10 -> 11)

This is only when the step (k) is 1, as shown by the following example:

slice3 = slice(1, 11, 2)
list3 = list(range(20))
print(list3, len(list3))
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] 20
list3[slice3] = [None] * 6 #s[i:j:k] = t | the elements of s[i:j:k] are replaced by those of _t_
#ValueError: attempt to assign sequence of size 6 to extended slice of size 5
#Length of list (can't) increase(s) by 1 (20 -> 21)

Since the example s[i:j:k] = t does not behave the same when k = 1 compared to k > 1, the documentation should be updated. My proposed change is footnote (1) reads as follows:

  1. If k = 1, then this behaves the same as s[i:j] = t, otherwise t must have the same length as the slice it is replacing. If t is not the same length as the slice it is replacing and k does not equal 1, then a ValueError is raised.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsDocumentation in the Doc dir

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions