How to slice a list from an element n to the end i

2019-02-03 00:15发布

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, 5, 6, 7, 8, 9]
>>> test[3:-1]
[3, 4, 5, 6, 7, 8]
>>> test[3:0]
[]
>>> test[3:1]
[]
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

To my understanding, python slice means lst[start:end], and including start, excluding end. So how would i go about finding the "rest" of a list starting from an element n?

Thanks a lot for all your help!

6条回答
等我变得足够好
2楼-- · 2019-02-03 00:42

You can leave one end of the slice open by not specifying the value.

test[3:] = [3, 4, 5, 6, 7, 8, 9]
test[:3] = [0, 1, 2]
查看更多
该账号已被封号
3楼-- · 2019-02-03 00:45

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)
查看更多
混吃等死
4楼-- · 2019-02-03 00:51

Simply omit the end.

test[n:]
查看更多
仙女界的扛把子
5楼-- · 2019-02-03 00:53

Leaving out the end still works when you want to skip some:

range(10)[3::2] => [3, 5, 7, 9]
查看更多
放荡不羁爱自由
6楼-- · 2019-02-03 01:06

Return a slice of the list after a starting value:

list = ['a','b','c','d']
start_from = 'b' # value you want to start with
slice = list[list.index(start_from):] # returns slice from starting value to end
查看更多
干净又极端
7楼-- · 2019-02-03 01:07

If you're using a variable as the range endpoint, you can use None.

 start = 4
 end = None
 test[start:end]
查看更多
登录 后发表回答