5

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]
Ali AzG
  • 1,861
  • 2
  • 18
  • 28

3 Answers3

2

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']
b-fg
  • 3,959
  • 2
  • 28
  • 44
1

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]
Siyanew
  • 542
  • 1
  • 4
  • 20
0

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