Skip to content Skip to sidebar Skip to footer

Slicing To Reverse Part Of A List In 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

Solution 1:

Use None if begin is 0:

mysublist = mylist[end - 1:Noneifnotbeginelsebegin - 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 notbeginelsebegin-1, -1
mysublist = mylist[start:stop:step]

Demo:

>>> mylist = ['foo', 'bar', 'baz', 'eggs']
>>> begin, end = 1, 3
>>> mylist[end - 1:Noneifnotbeginelsebegin - 1:-1]
['baz', 'bar']
>>> begin, end = 0, 3
>>> mylist[end - 1:Noneifnotbeginelsebegin - 1:-1]
['baz', 'bar', 'foo']

Solution 2:

You could simply collapse your two lines into one:

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

Solution 3:

You can always use the power of functional transformations:

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

Post a Comment for "Slicing To Reverse Part Of A List In Python"