How to trim a list in Python

后端 未结 4 623
轮回少年
轮回少年 2020-12-14 05:48

Suppose I have a list with X elements

[4,76,2,8,6,4,3,7,2,1...]

I\'d like the first 5 elements. Unless it has less than 5 elements.

<
4条回答
  •  爱一瞬间的悲伤
    2020-12-14 06:22

    To trim a list in place without creating copies of it, use del:

    >>> t = [1, 2, 3, 4, 5]
    >>> # delete elements starting from index 4 to the end
    >>> del t[4:]
    >>> t
    [1, 2, 3, 4]
    >>> # delete elements starting from index 5 to the end
    >>> # but the list has only 4 elements -- no error
    >>> del t[5:]
    >>> t
    [1, 2, 3, 4]
    >>> 
    

提交回复
热议问题