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
2010-06-01 07:13:35
Interesting.. thanks for the quick reply.
Sam
2010-06-01 07:14:12
@Sam please mark it as the answer if you are satisfied.
Geoffrey Van Wyk
2010-06-01 07:40:24