2

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))
Adirio
  • 4,839
  • 1
  • 14
  • 25
Bhargav v
  • 35
  • 3
  • 4
    That's a really silly way of doing `list(string)` – juanpa.arrivillaga Sep 08 '20 at 06:34
  • 1
    In any case, slice-assignment essentially "extends" into the slice range, overwriting anything inside that slice range, but not anything beyond it. The example you showed is needlessly confusing and undiomatic. So consider, `data = [0, 1, 2, 3, 4]; data[1:3] = "ABCDEFG"` – juanpa.arrivillaga Sep 08 '20 at 06:36
  • 1
    The question is not about the best practice of doing this action. it is about how it works – Mehrdad Pedramfar Sep 08 '20 at 06:37
  • 2
    Note that you shouldn't so much worry how this works, rather why someone would use such a convoluted code. Yes, it makes sense if one is familiar with Python. No, there is no reason to actually do it that way. – MisterMiyagi Sep 08 '20 at 06:37
  • 2
    @MehrdadPedramfar yes, I understand that but it **really** should be pointed out that the code as written is silly and needlessly confusing – juanpa.arrivillaga Sep 08 '20 at 06:38
  • 1
    @juanpa.arrivillaga I believe that OP see's this code here: https://www.geeksforgeeks.org/python-program-convert-string-list/ – Mehrdad Pedramfar Sep 08 '20 at 06:38
  • So, if you do slice assignment, `data[n:n]` it inserts/extends the sequence at `n` without overwriting anythingin the sequence. So `list1[:0]` is essentially equivalent to `list1[0:0]` so it just inserts everything at the beginning, since the list is empty anyway – juanpa.arrivillaga Sep 08 '20 at 06:39
  • @MehrdadPedramfar ok, it is silly code that should never be written like that and it would be excoriated in any sane code review at any place with a modicum of standards. But thanks for finding that, it's disappointing, Geeks for Geeks is usually an OK source. – juanpa.arrivillaga Sep 08 '20 at 06:40
  • 1
    I agree. @juanpa.arrivillaga – Mehrdad Pedramfar Sep 08 '20 at 06:42
  • What parts of this *do* you understand? Are you aware of [slice assignment](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types)? – MisterMiyagi Sep 08 '20 at 06:43
  • Does this answer your question? [How assignment works with Python list slice?](https://stackoverflow.com/questions/10623302/how-assignment-works-with-python-list-slice) – MisterMiyagi Sep 08 '20 at 06:45

1 Answers1

2

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

Rajat Tyagi
  • 211
  • 4
  • 6