0

To convert a string to char-wise list, one way is to assign the string to an empty list. However, the physical process on the memory is unclear to me. Any help is appreciated.

An example

s = 'abc'
s_list = []
s_list[:5] = s
print(s_list)

The code will output: ['a', 'b', 'c']

Basically, I would like to understand:

  1. Why there is no out of index error when you try to do slicing s_list[:5] on an empty list? As a matter of fact, you can do s_list[:] or s_list[x:] or s_list[:x] (x can be any integer), it wouldn't raise any error.
  2. I would like to know what's happening at the assignment sign for s_list[:5] = s. Does Python do a automatic conversion from string to list before assign to s_list?
Roy
  • 53
  • 5

1 Answers1

0
  1. documentation of python std library, paragraph on sequence types https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range see footnote #4
  2. I believe that taking a slice of an existing list and assigning to it some iterable (including string) will use values of that iterable to fill the slice, e.g.

l=[];
l[0:5] = range(5);
 
JVod
  • 151
  • 5
  • thanks, I guess for 1. "If i or j is greater than len(s), use len(s)" applies, so no matter what number is used for the start, end of slicing, Python will convert them all to 0, which is the length of an empty string. 2. If so, does it make any difference if I use l[:1] = range(5), l[:2] = range(5), l[1:] = range(5), l[2:] = range(5), or...? – Roy Jan 26 '21 at 04:33
  • @Roy, when a colon is used, a slice object is created; it`s different from when a numeric index is used. I tried to sublass a list an see is internal workings, but failed, list processes slices on __setitem__ call without alling append/insert etc; documentation that i`ve searched thru also gives no answer to this. The only _noticeable_(maybe there`s difference in inner workings) difference will emerge when the list is not empty, and its slice is replaced with given object. e.g. take assignments from your comment, perform them on l = list(range(5)), initialize before and consider contents of l – JVod Jan 26 '21 at 05:18
  • 1
    I did some experiments and things start to become clear. 1. if the index "i or j is greater than len(s), use len(s)", which can be translated to, no matter what number(s) are used in the bracket, for an empty list, it always equal to [:]. 2. The slice will point to the index given in the bracket, in the case of empty list, the end/start of this empty list. Then the string will be assigned starting from this index. Here is an example, `a = ['a','b','c'] print(a[2:5]) a[2:5] = 'abcdef' print(a)` Note that the string was assigned to the list starting from a[2]. – Roy Jan 28 '21 at 18:27