Op 26/11/2021 om 10:17 schreef Frank Millman:
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?

It depends. Since you are talking about x being a fairly long expression,
how about adapting that expression so that is produces the reverse of
what is now produced and then use the [y:] slice?

You can also adapt the y expression so that instead of y it produces
len(x) - y.

You may consider writing a reverse_view function, that takes a list
as argument and produces something that behaves as the reversed list
without actually reversing the list and then as in the first option
use the [y:] slice on that.

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

Reply via email to