+ 2

How does this programme works?Can you explain

def convert_to_list(string): list=[] list[:0]=string return(list) #this function returns the character wise list of the string

22nd Sep 2020, 4:42 PM
Abhisindh Chatterjee
Abhisindh Chatterjee - avatar
1 ответ
+ 2
list[:0]=string That line is key. That inserts each and every character from the string as a separate element in the list. For example, list = [] list[:0] = 'hello' Now, list will be ['h', 'e', 'l', 'l', 'o']. Assigning an iterable to a range in a list replaces the specified range with all iterable elements. That's just a feature of the Python programming language and the list data type. If you want to see a little more discussion about assigning to these list ranges, check discussion at https://www.sololearn.com/Discuss/2744104/list-slice-problem-in-python Note that your convert_to_list function is quite redundant. It is useful for educational purposes but any string can be converted to the same list by just wrapping your string in the list function like list('hello'). list('hello') is ['h', 'e', 'l', 'l', 'o'].
3rd Apr 2021, 9:07 AM
Josh Greig
Josh Greig - avatar