0

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?

pani3610
  • 83
  • 1
  • 4
  • 5
    A much more simple way to do the same would be `l = list(s)`. I'm considering that Example 3 a bad example that you should forget again. – mkrieger1 Mar 24 '22 at 19:37
  • You can [find some more reading here](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements). I think you're right to be suspicious of this code. This is a difficult to read way of doing this operation and should be avoided. – Patrick Haugh Mar 24 '22 at 19:42
  • @mkrieger1 yes it does! I went with the above method because I remember when I tried `l = list('abc')` it returned `['abc']`. But today I checked its returning `['a','b','c']` as it should. I just need to revisit and see what I did wrong yesterday – pani3610 Mar 24 '22 at 19:51

1 Answers1

0

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

kosciej16
  • 6,294
  • 1
  • 18
  • 29
  • OP had `l[:0]` which actually replaces the *front* of the list so if `l` is not empty you get: `l = [0,1,2,3]; l[:0] = [4,5,6]` -> `[4, 5, 6, 0, 1, 2, 3]`. – Mark Tolonen Mar 24 '22 at 20:10
  • indeed you are right, it's kinda misleading as example of converting string to list... – kosciej16 Mar 24 '22 at 20:13