1

I have this code in python:

string_a = "abcdef"
list_a = []
list_a[:0] = string_a

and it outputs ["a","b","c","d","e","f"] and although this is exactly what I want I don't understand how it worked. this [:0] basically means that we start from the beginning of the list and stop at the beginning, we have an empty list. After that we assign the value of the string to the empty list and then I don't understand what happens anymore.

How did the string got split into a list of single characters?

  • 1
    When you assign to a slice, it replaces that slice with whatever you're assigning. So it will insert or delete if the new sequence is longer or shorter than the slice. – Barmar Jun 21 '22 at 09:06
  • *"`[:0]` basically means that we start from the beginning of the list and stop at the beginning"* - Yes, but you're applying slice on `list_a`, not on `string_a`. So basically you're replacing all elements in list from `0` to `0` index with content of `string_a`. – Olvin Roght Jun 21 '22 at 09:06

2 Answers2

0

As @Barmar explained in the comments, all elements from the iterable on the right hand side of the assignment are inserted, and the list grows as necessary.

It's probably clearer with these examples:

stop != start

>>> l = [0, 1, 2, 3]
>>> l[1:2] = 'abc'
>>> l
[0, 'a', 'b', 'c', 2, 3]

stop = start

>>> l = [0, 1, 2, 3]
>>> l[1:1] = 'abc'
>> l
[0, 'a', 'b', 'c', 1, 2, 3]
timgeb
  • 76,762
  • 20
  • 123
  • 145
0

what you're doing is you're replacing that segment of the "list_a" with whatever value you give it. for example:

string_a = "abcdef"
list_a = []
list_a[:0] = string_a

>> list_a
>> ['a', 'b', 'c', 'd', 'e', 'f']

>> list_a[:3] = "123"
>> list_a
>> ['1', '2', '3', 'd', 'e', 'f']
Amir
  • 129
  • 4