Negative subscripts
Chris Angelico
rosuav at gmail.com
Fri Nov 26 06:24:16 EST 2021
On Fri, Nov 26, 2021 at 10:11 PM Rob Cliffe via Python-list
<python-list at python.org> wrote:
> or, perhaps simplest, you could do
>
> for item in x[:-y or None]: # a value of None for a slice argument means
> "don't slice here"
> [do stuff]
>
This is the one I'd recommend. If you're negating a slice like this,
just add "or None" to handle negative zero as the other end of the
list.
Be aware that this will still slice even if you're going to use the
whole list, unlike the "x[-y] if y else x" approach, which will
iterate over the original list. That might be important.
ChrisA
More information about the Python-list
mailing list