Issue
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?
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]
Answered By - timgeb
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.