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
Post a Comment