Search code examples
pythonslicevariable-assignment

Explanation of iterable object assignment in specific range by list slicing (ex, arr[1:3] = 'ABCD')


arr = [1, 2, 3, 4, 5]
arr[1:3] = 'ABCD'
arr
[1, 'A', 'B', 'C', 'D', 4, 5]

Exactually, this code is useless. I don't think anyone uses python lists like this. But i wanna know about the result just because of curiosity.

I can know something intuitively seeing result.

old arr[1:3] (2, 3) is gone and replaced by string 'ABCD' sequentially.

But just fact about results, I can't understand how it works.

Can I get some hint or docs for understand this result?


Solution

  • Slice assignment takes an iterable on the right-hand. Many things can be iterables, an array or list, for example [8, 9]:

    arr = [1, 2, 3, 4, 5]
    arr[1:3] = [8, 9]
    arr
    [1, 8, 9, 4, 5]
    

    A string is an iterable of characters, as you can see in this example

    for x in 'ABCD':
        print(x)
    A
    B
    C
    D
    

    which is why get the result you got. So if what you want is to replace the arr[1:3] slice with a single array element that's a string, you need to give it an iterable that yields that element:

    arr = [1, 2, 3, 4, 5]
    arr[1:3] = ['ABCD']
    arr
    [1, 'ABCD', 4, 5]
    

    Note the brackets around the string in the slice assignment statement.