Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cut off a varying length tail from a list elegantly?

Tags:

python

I'm fairly new to Python, and this is a rather basic question.

I've got a list lst and have at some point computed an integer n with 0<=n<=len(lst) that tells me that (for the purpose at hand) I should discard the final n elements of the list. The statement that comes to mind to achieve this is del lst[-n:] or maybe lst[-n:]=[] (I've found out that in either case adding 0 after the colon is not a good idea, as zero is not considered to be larger than -n in this setting). However both variants fail when n==0, as the list gets emptied entirely instead. Should I really insert an explicit test for zero here, or stoop down to writing

del lst[len(lst)-n:]

or is there something more elegant (and reliable) that can be done here?

like image 871
Marc van Leeuwen Avatar asked Oct 21 '22 12:10

Marc van Leeuwen


1 Answers

After consideration of other possibilities suggested, I conclude that

del lst[len(lst)-n:]  # do not remove the len(lst) since n==0 is possible !

is as clean as it gets. The computation of len(lst) may not be very beautiful, but the cost it represents is negligible.

Added much later: The problem here stems from the fact that the interpretation of an index expression as a boundary "counting from the right", is dynamically determined from the runtime value of the expression (namely that it is negative), together with the fact that the value 0, being already used as indicating the leftmost boundary, cannot also mean the rightmost boundary. If the feature were determined from a syntactic feature, then it would be perfectly possible to specify without explicit arithmetic the boundary that is i places from the right, where i could well be 0. It would not be possible to write a single expression where some bound in it is sometimes interpreted from the left and sometimes from the right, depending on the runtime status, but that is something one hardly ever wants to do anyway.

like image 66
Marc van Leeuwen Avatar answered Oct 24 '22 10:10

Marc van Leeuwen