Python slice first and last element in list

后端 未结 17 1452
有刺的猬
有刺的猬 2020-12-02 17:54

Is there a way to slice only the first and last item in a list?

For example; If this is my list:

>>> some_list
[\'1\', \'B\', \'3\', \'D\',          


        
17条回答
  •  萌比男神i
    2020-12-02 18:49

    You can use something like

    y[::max(1, len(y)-1)]
    

    if you really want to use slicing. The advantage of this is that it cannot give index errors and works with length 1 or 0 lists as well.

提交回复
热议问题