How to cut (in Python) "everything except the last n" elements, when n can be zero?

I have a list of elements in Python, and I need to get "everything but the last N" elements. It should work when N is zero (in this case I want the whole list), and when N is greater than or equal to the length of the list (in this case I need an empty list). This works in most cases:

mylist=[0,1,2,3,4,5,6,7,8,9] print( mylist[:-n] ) 

But this fails when N is zero. mylist[:0] returns an empty list: [] . Is there a Python slicing notation that will do what I want, or a simple function?

+7
python slice
source share
1 answer

You can pass None to slice

 print(mylist[:-n or None]) 
+19
source share

All Articles