I'm confused how the following python code works to split a string to individual characters using b[:0] = a
. Shouldn't it be just b = ['abc']
?
a='abc'
b=[]
b[:0]=a
print(b)
output:
b=[a,b,c]
This is because the list constructor can be used to split any iterables, such as strings.
You do not even need [:0]
,
list(a) # ['a', 'b', 'c']
or,
b = []
b[:] = a # ['a', 'b', 'c']
According to Python Doc whenever left side of assignment statement is slicing, python do __setitem__
so in this case it put right side items in the beginning of slicing. take a look at this example:
>>> a = [1,2,3,4]
>>> b = [5,6,7,8]
>>> b[3:5] = a
>>> print(b)
[5, 6, 7, 1, 2, 3, 4]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With