Slicing to reverse part of a list in python

I have a list from which I want to extract a sub-layer from end to end. With two lines of code, this is

mylist = [...]
mysublist = mylist[begin:end]
mysublist = mysublist[::-1]

      

Is there a notation for slicing to get the same effect in one line? it

mysublist = mylist[end:begin:-1]

      

is incorrect because it includes end

and excludes items begin

. it

mysublist = mylist[end-1:begin-1:-1]

      

doesn't work when begin

0, because begin-1

now -1

that is interpreted as the index of the last element mylist

.

+3


source to share


3 answers


Use None

if begin

- 0

:

mysublist = mylist[end - 1:None if not begin else begin - 1:-1]

      

None

means "default", the same as omitting a value.

You can always put the conditional on a separate line:



start, stop, step = end - 1, None if not begin else begin - 1, -1
mysublist = mylist[start:stop:step]

      

Demo:

>>> mylist = ['foo', 'bar', 'baz', 'eggs']
>>> begin, end = 1, 3
>>> mylist[end - 1:None if not begin else begin - 1:-1]
['baz', 'bar']
>>> begin, end = 0, 3
>>> mylist[end - 1:None if not begin else begin - 1:-1]
['baz', 'bar', 'foo']

      

+4


source


You can simply collapse two lines into one:



mysublist = mylist[begin:end][::-1]

      

+2


source


You can always use the power of functional transformations:

mysublist = list(reversed(mylist[begin:end]))

      

+1


source







All Articles