python - Slice Assignment with a String in a List -
i did quite bit of perusing, don't have definite answer concept i'm trying understand.
in python, if take list, such as:
l1=['muffins', 'brownies','cookies'] and attempted replace first pointer object in list, namely 'muffins' using code:
l1[0:1] = 'cake' i list l1:
['c', 'a', 'k', 'e', 'brownies', 'cookies'] yet if took same list , performed operation (now 4 elements string cake):
l1[0:4] = ['cake'] # presumably, it's passing string cake within list? i output desired:
['cake', 'brownies', 'cookies'] can explain why is, exactly? i'm assuming when take cake without being in "list", breaks string individual characters stored references characters opposed single reference string...
but i'm not entirely sure. first post, i'm not entirely sure i'm following doctrine said i'd adhere correctly, attempt, suppose. thank you.
two important points:
- slice assignment takes an iterable on right-hand side, , replaces elements of slice objects produced iterable.
- in python, strings iterable: iterating on string yields characters.
thus
l1[0:1] = 'cake' replaces first element of l1 the individual characters of 'cake'.
to replace first element string 'cake', write:
l1[0] = 'cake' or, using slice assignment syntax:
l1[0:1] = ['cake']
Comments
Post a Comment