1
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?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
PSW
  • 59
  • 6
  • 1
    `foo[x:y] = z` is effectively equivalent to `foo[:x] + list(z) + foo[y:]`, except the elements of `list(z)` are inserted in-place, instead of building a new list. – chepner Jun 20 '21 at 16:41
  • 1
    Does this answer your question? [How assignment works with Python list slice?](https://stackoverflow.com/questions/10623302/how-assignment-works-with-python-list-slice) Note that [this answer](/a/10623383/4518341) is much more thorough than the accepted answer. – wjandrea Jun 20 '21 at 16:44

1 Answers1

2

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.

joao
  • 2,220
  • 2
  • 11
  • 15