Negative subscripts

Pieter van Oostrum pieter-l at vanoostrum.org
Fri Nov 26 09:08:18 EST 2021


Frank Millman <frank at chagford.com> writes:

> Hi all
>
> In my program I have a for-loop like this -
>
>>>> for item in x[:-y]:
> ...    [do stuff]
>
> 'y' may or may not be 0. If it is 0 I want to process the entire list
> 'x', but of course -0 equals 0, so it returns an empty list.
>
> In theory I can say
>
>>>> for item in x[:-y] if y else x:
> ...    [do stuff]
>
> But in my actual program, both x and y are fairly long expressions, so
> the result is pretty ugly.
>
> Are there any other techniques anyone can suggest, or is the only
> alternative to use if...then...else to cater for y = 0?

If you put it in a function with x and y as parameters, then both x and y are just a simple identifier inside the function.
And then you can then even eliminate the if with

for item in x[:len(x)-y]:
-- 
Pieter van Oostrum <pieter at vanoostrum.org>
www: http://pieter.vanoostrum.org/
PGP key: [8DAE142BE17999C4]


More information about the Python-list mailing list