Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the first Item from a list?

I have the list [0, 1, 2, 3, 4] I'd like to make it into [1, 2, 3, 4]. How do I go about this?

like image 247
rectangletangle Avatar asked Dec 13 '10 07:12

rectangletangle


People also ask

How do I remove the first element from a list in Python O 1?

Method 5: Remove Elements From Lists in Python using remove() The remove() function allows you to remove the first instance of a specified value from the list. This can be used to remove the list's top item.

How do I remove the first element from a list in Java?

We can use the remove() method of ArrayList container in Java to remove the first element. ArrayList provides two overloaded remove() method: remove(int index) : Accept index of the object to be removed. We can pass the first element's index to the remove() method to delete the first element.

How do I remove all 1 from a list in Python?

Use the remove() Function to Remove All the Instances of an Element From a List in Python. The remove() function only removes the first occurrence of the element. If you want to remove all the occurrence of an element using the remove() function, you can use a loop either for loop or while loop.

How do I remove an item from a list?

Use del to remove an element by index, pop() to remove it by index if you need the returned value, and remove() to delete an element by value. The last requires searching the list, and raises ValueError if no such value occurs in the list.


1 Answers

You can find a short collection of useful list functions here.

list.pop(index)

>>> l = ['a', 'b', 'c', 'd'] >>> l.pop(0) 'a' >>> l ['b', 'c', 'd'] >>>  

del list[index]

>>> l = ['a', 'b', 'c', 'd'] >>> del l[0] >>> l ['b', 'c', 'd'] >>>  

These both modify your original list.

Others have suggested using slicing:

  • Copies the list
  • Can return a subset

Also, if you are performing many pop(0), you should look at collections.deque

from collections import deque >>> l = deque(['a', 'b', 'c', 'd']) >>> l.popleft() 'a' >>> l deque(['b', 'c', 'd']) 
  • Provides higher performance popping from left end of the list
like image 79
kevpie Avatar answered Sep 28 '22 09:09

kevpie