Slice Assignment with a String in a List

indexing, python, slice, string

Solution

Two important points:

- Slice assignment takes an iterable on the right-hand side, and replaces the elements of the slice with the objects produced by the iterable.

- In Python, strings are iterable: iterating over a string yields its characters.

Thus

L1[0:1] = 'cake'

replaces the first element of `L1` with the individual characters of `'cake'`.

To replace the first element with the string `'cake'`, simply write:

L1[0] = 'cake'

or, using the slice assignment syntax:

L1[0:1] = ['cake']

Problem

I did quite a bit of perusing, but I don't have a definite answer for the concept that I'm trying to understand. In Python, if I take a list, such as: ``` L1=['muffins', 'brownies','cookies'] ``` And then attempted to replace the first pointer to an object in the list, namely 'muffins' by using the code: ``` L1[0:1] = 'cake' ``` I would get a list L1: ``` ['c', 'a', 'k', 'e', 'brownies', 'cookies'] ``` Yet if I took the same list and performed the operation (now with the 4 elements from the string cake): ``` L1[0:4] = ['cake'] # presumably, it's now passing the string cake within a list? (it passed into the modified list shown above) ``` I get the output I initially desired: ``` ['cake', 'brownies', 'cookies'] ``` Can anyone explain why that is, exactly? I'm assuming that when I take cake initially without it being in a "list", it breaks the string into its individual characters to be stored as references to those characters as opposed to a single reference to a string... But I'm not entirely sure.

Original source

Related problems