Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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

like image 264
Sam Avatar asked Jun 01 '10 07:06

Sam


People also ask

How does slicing work in python list?

With this operator, one can specify where to start the slicing, where to end, and specify the step. List slicing returns a new list from the existing list. If Lst is a list, then the above expression returns the portion of the list from index Initial to index End, at a step size IndexJump.

How do you slice a value in a list in python?

You can generate a slice object using the built-in function slice() . If you want to repeatedly select the items at the same position, you only need to generate the slice object once. slice(start, stop, step) is equivalent to start:stop:step . If two arguments are specified, step is set to None .

Can we do slicing in list?

As well as using slicing to extract part of a list (i.e. a slice on the right hand sign of an equal sign), you can set the value of elements in a list by using a slice on the left hand side of an equal sign. In python terminology, this is because lists are mutable objects, while strings are immutable.


1 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] 
like image 140
Amber Avatar answered Sep 19 '22 10:09

Amber