Python: How do you insert into a list by slicing?

前端 未结 2 2002
长情又很酷
长情又很酷 2021-02-01 14:43

I was instructed to prevent this from happening in a Python program but frankly I have no idea how this is even possible. Can someone give an example of how you can slice a list

2条回答
  •  情书的邮戳
    2021-02-01 15:14

    >>> a = [1,2,3]
    >>> a[:0] = [4]
    >>> a
    [4, 1, 2, 3]
    

    a[:0] is the "slice of list a beginning before any elements and ending before index 0", which is initially an empty slice (since there are no elements in the original list before index 0). If you set it to be a non-empty list, that will expand the original list with those elements. You could also do the same anywhere else in the list by specifying a zero-width slice (or a non-zero width slice, if you want to also replace existing elements):

    >>> a[1:1] = [6,7]
    >>> a
    [4, 6, 7, 1, 2, 3]
    

提交回复
热议问题