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

Question:

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 and insert something into it to make it bigger? Thanks

Asked By: Sam

||

Answers:

>>> 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]
Answered By: Amber

To prevent this from happening you can subclass the builtin list and then over-ride these methods for details refer here

Answered By: anijhaw
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.