How to gracefully cut a tail of variable length from a list?

I am new to Python and this is a pretty simple question.

I have a list lst and at some point an integer n calculated with 0<=n<=len(lst) , which tells me that (for this purpose) I should discard the final elements of n in the list, The statement that comes to mind to achieve this, del lst[-n:] or maybe lst[-n:]=[] (I found that in any case, adding 0 after the colon is not a good idea, since zero is not considered large, than -n in this setting). However, both options fail if n==0 , since the list is completely empty. Do I really have to insert an explicit test for zero here or bend down before writing

 del lst[len(lst)-n:] 

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

+4
source share
1 answer

After considering the other proposed features, I conclude that

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

as clean as he is. The calculation of len(lst) may not be very pretty, but the cost it represents is negligible.

+2
source

All Articles