How to slice a list from an element n to the end in python?

前端 未结 7 1822
[愿得一人]
[愿得一人] 2020-12-29 01:24

I\'m having some trouble figuring out how to slice python lists, it is illustrated as follows:

>>> test = range(10)
>>> test
[0, 1, 2, 3, 4         


        
7条回答
  •  长情又很酷
    2020-12-29 01:32

    You can also use the None keyword for the end parameter when slicing. This would also return the elements till the end of the list (or any sequence such as tuple, string, etc.)

    # for list
    In [20]: list_ = list(range(10))    
    In [21]: list_[3:None]
    Out[21]: [3, 4, 5, 6, 7, 8, 9]
    
    # for string
    In [22]: string = 'mario'
    In [23]: string[2:None]
    Out[23]: 'rio'
    
    # for tuple
    In [24]: tuple_ = ('Rose', 'red', 'orange', 'pink', 23, [23, 'number'], 12.0)
    In [25]: tuple_[3:None]
    Out[25]: ('pink', 23, [23, 'number'], 12.0)
    

提交回复
热议问题