python - How to slice middle element from list -


rather simple question. have list like:

a = [3, 4, 54, 8, 96, 2] 

can use slicing leave out element around middle of list produce this?

a[some_slicing] [3, 4, 8, 96, 2] 

were element 54 left out. would've guessed trick:

a[:2:] 

but result not expected:

[3, 4] 

you cannot emulate pop single slice, since slice gives single start , end index.

you can, however, use 2 slices:

>>> = [3, 4, 54, 8, 96, 2] >>> a[:2] + a[3:] [3, 4, 8, 96, 2] 

you wrap function:

>>> def cutout(seq, idx):         """         remove element @ `idx` `seq`.         todo: error checks.         """         return seq[:idx] + seq[idx + 1:]  >>> cutout([3, 4, 54, 8, 96, 2], 2) [3, 4, 8, 96, 2] 

however, pop faster. list pop function defined in listobject.c.


Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -