can't understand how assigning characters in string to list through list slicing works in following piece of code

Viewed 199

I can't understand how string is assigned to the list

def convert(string): 
    list1 = []
    list1[:0] = string 
    return list1 

# Driver code 
str1 = "ABCD"
print(convert(str1))
1 Answers

As it looks its a way of converting a string to a list, you can do it like

list(string)

but this is also quite interesting as , it takes whatever is the input the append it in the start of the list, from python docs list insertion

list1[0:0] inserts the iterable to before the first element of the list, if you slice the list to go up to zero elemen it gives you an empty list

Related