Home > OS >  I don't how this list slicing works, can anybody explain?
I don't how this list slicing works, can anybody explain?

Time:06-21

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?

CodePudding user response:

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]

CodePudding user response:

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']
  • Related