I need to remove the first n elements from a list of objects in Python 2.7. Is there an easy way, without using loops?
The remove() method removes the first matching element (which is passed as an argument) from the list. The pop() method removes an element at a given index, and will also return the removed item. You can also use the del keyword in Python to remove an element or slice from a list.
To remove the first n elements from an array:Call the splice method on the array, passing it the start index and the number of elements to remove as arguments. For example, arr. splice(0,2) removes the first two elements from the array and returns a new array containing the removed elements.
To access the first n elements from a list, we can use the slicing syntax [ ] by passing a 0:n as an arguments to it . 0 is the start index (it is inculded). n is end index (it is excluded).
You can use list slicing to archive your goal.
Remove the first 5 elements:
n = 5 mylist = [1,2,3,4,5,6,7,8,9] newlist = mylist[n:] print newlist
Outputs:
[6, 7, 8, 9]
Or del
if you only want to use one list:
n = 5 mylist = [1,2,3,4,5,6,7,8,9] del mylist[:n] print mylist
Outputs:
[6, 7, 8, 9]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With