1

Good day I just want to understand the logic behind this code

lst = []
word = "ABCD"
lst[:0] = word

print(lst)

OUTPUT: ['A', 'B', 'C', 'D'] why not ['ABCD'] how?

for i in word: # this code I understand it's looping through the string
  lst.append(i) # then appending to list

but the first code above I don't get the logic.

Jethro
  • 31
  • 5
  • check https://stackoverflow.com/questions/39541370/how-to-insert-multiple-elements-into-a-list – Epsi95 Jul 11 '21 at 14:24
  • 4
    You're assigning to a slice, so it treats `word` as an iterable. To get what you want, you need `lst[:0] = [word]`. This will insert `word` to the front of `lst`. If you instead want to overwrite the entire list (e.g., if it's non-empty), you can do `lst[:] = [word]`. – Tom Karzes Jul 11 '21 at 14:26
  • I'm not sure what the original rationale was for making a `str` an iterable of `str`s, rather than having a separate non-iterable type `char`. – chepner Jul 11 '21 at 14:31

2 Answers2

2

lst[:0] = ... is implemented by lst.__setitem__(slice(0, None, 0), ...), where ... is an arbitrary iterable.

The resulting slice is the empty list at the beginning of lst (though in this case, it doesn't really matter since lst is empty), so each element of ... is inserted into lst, starting at the beginning.

You can see this starting with a non-empty list.

>>> lst = [1,2,3]
>>> word = "ABCD"
>>> lst[:0] = word
>>> lst
['A', 'B', 'C', 'D', 1, 2, 3]

To get lst == ['ABCD'], you need to make the right-hand side an iterable containing the string:

lst[:0] = ('ABCD', )  # ['ABCD'] would also work.
chepner
  • 497,756
  • 71
  • 530
  • 681
1

Actually it's a well known way to convert string to a list character by character

you can find here -> https://www.geeksforgeeks.org/python-program-convert-string-list/

if you wanna try to get your list element like 'ABCD' then try

lst[:0] = [word,]

by doing that you specify that you need whole word as an element

Krenil
  • 96
  • 7