You could evaluate y separately:

yval = <long expression>
for item in x[:-yval] if yval else x:
    [do stuff]

or you could do it using the walrus operator:

for item in x[:-yval] if (yval := <long expression>) else x:
    [do stuff]

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]

Best wishes
Rob Cliffe

On 26/11/2021 09:17, Frank Millman wrote:
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?

Thanks

Frank Millman

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to