Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing to reverse part of a list in python

Tags:

python

I have a list, of which I want to extract a subslice from back to end. With two lines of code, this is

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

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

mysublist = mylist[end:begin:-1]

is incorrect, because it includes the end and excludes the begin elements. This

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

fails when begin is 0, because begin-1 is now -1 which is interpreted as the index of the last element of mylist.

like image 719
P-Gn Avatar asked Jan 04 '23 03:01

P-Gn


1 Answers

Use None if begin is 0:

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

None means 'default', the same thing as omitting a value.

You can always put the conditional expression 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']
like image 144
Martijn Pieters Avatar answered Jan 16 '23 17:01

Martijn Pieters