Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pop multiple items from the beginning and end of a list

Suppose I have a list of items like this:

mylist=['a','b','c','d','e','f','g','h','i'] 

I want to pop two items from the left (i.e. a and b) and two items from the right (i.e. h,i). I want the most concise an clean way to do this. I could do it this way myself:

for x in range(2):     mylist.pop()     mylist.pop(0) 

Any other alternatives?

like image 205
Ehsan88 Avatar asked Jun 16 '14 13:06

Ehsan88


People also ask

Can I pop multiple items from list Python?

Python pop() Function | First, by value, pop multiple Examples. Python pop function is used to remove a returns last object from the list. You can also remove the element at the specified position using the pop() function by passing the index value.

How do you pop the last two elements of a list in Python?

Method 3: Using pop() method: the pop() method will remove the last element from the list, So to remove last k elements from the python list, we need to perform the pop() operation k times.

How do you pop all elements in a list?

The methods are remove(), pop() and clear(). It helps to remove the very first given element matching from the list. The pop() method removes an element from the list based on the index given. The clear() method will remove all the elements present in the list.


1 Answers

From a performance point of view:

  • mylist = mylist[2:-2] and del mylist[:2];del mylist[-2:] are equivalent
  • they are around 3 times faster than the first solution for _ in range(2): mylist.pop(0); mylist.pop()

Code

iterations = 1000000 print timeit.timeit('''mylist=range(9)\nfor _ in range(2): mylist.pop(0); mylist.pop()''', number=iterations)/iterations print timeit.timeit('''mylist=range(9)\nmylist = mylist[2:-2]''', number=iterations)/iterations print timeit.timeit('''mylist=range(9)\ndel mylist[:2];del mylist[-2:]''', number=iterations)/iterations 

output

1.07710313797e-06

3.44465017319e-07

3.49956989288e-07

like image 53
mxdbld Avatar answered Sep 21 '22 13:09

mxdbld