简体   繁体   中英

Popping the last element of a one-dimensional array

When it comes to list s, we all know and love good old pop , which removes the last item from the list and returns it:

>>> x = range(3)
>>> last_element = x.pop()
>>> last_element
2
>>> x
[0, 1]

But suppose I'm using a one-dimensional numpy array to hold my items, because I'm doing a lot of elementwise computations. What then is the most efficient way for me to achieve a pop ?

Of course I can do

>>> import numpy as np
>>> x = np.arange(3)
>>> last_element = x[-1]
>>> x = np.delete(x, -1)  # Or x = x[:-1]
>>> last_element
2
>>> x
array([0, 1])

And, really, when it comes down to it, this is fine. But is there a one-liner for arrays I'm missing that removes the last item and returns it at the same time?

And I'm not asking for

>>> last_element, x = x[-1], x[:-1]

I'm not counting this as a one-liner, because it's two distinct assignments achieved by two distinct operations. Syntactic sugar is what puts it all on one line. It's a sugary way to do what I've already done above. (Ha, I was sure someone would rush to give this as the answer, and, indeed, someone has. This answer is the equivalent of my asking, "What's a faster way to get to the store than walking?" and someone answering, "Walk, but walk faster." Uh . . . thanks. I already know how to walk.)

There is no such one liner for numpy (unless you write your own). numpy is meant to work on fixed sized objects (or objects that change less frequently). So by that metric a regular old python list is better for popping.

You are correct in that element-wise operations are better with numpy . You're going to have to profile out your code and see which performs better and make a design decision.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM