'Why does this implementation of conversion of string to a list of characters work? [duplicate]
As referenced as Example 3 here for converting a string to a list of characters:
l = []
s = 'abc'
l[:0]=s
print(l) #Output is ['a','b','c']
My question is how intuitive or logical it is that line 3 does what it does? Is it something one can deduce/derive from a first principle? Or is it just an edge case? Are there any more such examples?
Solution 1:[1]
To acknowledge it as intuitive you need to know few things but mostly what slicing is.
Generally the slice is an object that represent some (non necessary compact) part of list.
l = [0,1,2,3,4,5]
l[0:2] # [0,1]
s = slice(0, 2)
l[s] # [0,1]
l[0:] # all list, actually should be just l[:]
python allows us to assign some iterable with such syntax
l[0:2] = "abcd" # it replaces proper sublist with right side
l # ['a','b','c','d',2,3,4,5]
l[0:] = [1,2,3] # replace all list with iterable on right side, one by one
Because string actually is an iterable, we put each character as new element of list. Notice it hasn't to have same lenght, it's more like cut slice and put insert new elements.
We could do that for non compact sublists too:
l[0::2] = "abc" # replace every second element with next element of iterable "abc"
l # ['a',1,'b',2,'c',3]
l[0::2] = [1] # ValueError: attempt to assign sequence of size 1 to extended slice of size 3
But in that case length of both sides must match
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
