Jethro
Jethro

Reputation: 31

Python string to list per character

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.

Upvotes: 1

Views: 492

Answers (2)

Krenil
Krenil

Reputation: 106

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

Upvotes: 1

chepner
chepner

Reputation: 530970

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.

Upvotes: 2

Related Questions