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]
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]
It's two things at play here
When you do
b[:0] = <something>
The something is inserted to the beginning of the list (This is appending to a list slice)
If you did
b[1:3] = ['a', 'b', 'c']
Then the items at index 1
and 2
are replaced by the items on the right
Try the following:
b = []
b[:0] = [1, 2, 3]
You will notice the items on the right inserted to the beginning of the list
Now when you do
b[:0] = "abc"
Since the items on the right hand side have to be a sequence, the string gets unpacked to ['a', 'b', 'c']
and then these are inserted to the beginning of the list