Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting string to individual characters using slicing

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]
like image 404
Praneeth N.C Avatar asked Oct 15 '22 04:10

Praneeth N.C


2 Answers

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']
like image 107
b-fg Avatar answered Oct 18 '22 13:10

b-fg


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]
like image 31
Siyanew Avatar answered Oct 18 '22 13:10

Siyanew