Negative subscripts

Edmondo Giovannozzi edmondo.giovannozzi at gmail.com
Fri Nov 26 04:36:04 EST 2021


Il giorno venerdì 26 novembre 2021 alle 10:23:46 UTC+1 Frank Millman ha scritto:
> 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

First assign your long expressions to variables x and y and then you may write:

for item in x[:len(x) - y]:
   ...



More information about the Python-list mailing list