Home > Blockchain >  Converting String to List by slicing: Possibly a Control Flow/ Syntax query
Converting String to List by slicing: Possibly a Control Flow/ Syntax query

Time:10-09

I found code that already converts a string to list, but I am trying to understand the part list1[:0]=string. Could you kindly explain to me how this would work? I understand the [:0] part.

What I am trying to understand is why the line is written the way it is written, because reading it from left to right doesn't make sense to me. I reckoned that the leftmost part would generally be a variable to which things would be assigned, which would happen using the = sign. Any explanation would be appreciated, and apologies for the Noob question.

# Python code to convert string to list character-wise
def Convert(string):
    list1=[]
    list1[:0]=string
    return list1

str1="ABCD"
print(Convert(str1))

CodePudding user response:

Ah, but it is a variable! We're just adding slice magic to our list (or more specifically, our sequence).

It's a bit easier to see what's going on if we extend the example a bit:

>>> my_list = []
>>> my_list[:0] = "1234"
>>> my_list
['1', '2', '3', '4']
>>> my_list[:0] = "5678"
>>> my_list
['5', '6', '7', '8', '1', '2', '3', '4'] 

The assignment operation is assigning the contents of the sequence (our string) to the positions in the list up to index 0 (which does not include index 0). Python helpfully automatically makes room at the front of the list, and then inserts the elements of the sequence (which in this case is a sequence of str from a str)

And if we take our example but instead slice [:1]?

>>> my_list[:1] = "ABCD"
>>> my_list
['A', 'B', 'C', 'D', '6', '7', '8', '1', '2', '3', '4']

As we assigned to a slice that extends to index 1 (which includes index 0, but not index 1), you can see that we have lost 5 from our list, with the contents of ABCD being added to the list at the beginning.

And to demonstrate from the other direction:

>>> my_list[-1:] = "EFGH"
>>> my_list
['A', 'B', 'C', 'D', '6', '7', '8', '1', '2', '3', 'E', 'F', 'G', 'H']

Now we have inserted the sequence starting at index -1 (or the last item in the sequence), and as such have lost 4 at the end of the list.

  • Related