Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading