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?
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.
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.
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.
From a performance point of view:
mylist = mylist[2:-2]
and del mylist[:2];del mylist[-2:]
are equivalentfor _ 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
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