tags:

views:

132

answers:

2

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

+9  A: 
>>> 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]
Amber
Interesting.. thanks for the quick reply.
Sam
@Sam please mark it as the answer if you are satisfied.
Geoffrey Van Wyk
A: 

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

anijhaw