Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The most efficient way to remove first N elements in a list?

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?

like image 470
RedVelvet Avatar asked Nov 10 '15 09:11

RedVelvet


People also ask

How do you remove the first n from a list in Python?

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.

How do you remove the first n elements from an array?

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.

How do you find the first N elements of a list?

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).


1 Answers

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] 
like image 170
Avión Avatar answered Oct 09 '22 20:10

Avión