Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 376
FurtiveFelon Avatar asked Mar 07 '09 05:03

FurtiveFelon


People also ask

How do you cut the end of a list in Python?

To access a range of items in a list, you need to slice a list. One way to do this is to use the simple slicing operator : With this operator you can specify where to start the slicing, where to end and specify the step.

Can we slice a list in Python?

Python supports slice notation for any sequential data type like lists, strings, tuples, bytes, bytearrays, and ranges. Also, any new data structure can add its support as well.

How do you slice the last 5 elements of a list in Python?

Method #2 : Using islice() + reversed() The inbuilt functions can also be used to perform this particular task. The islice function can be used to get the sliced list and reversed function is used to get the elements from rear end.


1 Answers

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] 
like image 181
Angela Avatar answered Oct 02 '22 09:10

Angela