I’ve been programming with Python for the last 4 years at my day job, and I’ve only seen this feature shown once in example code. To be honest, this is not something that you would use very often, but personally there are plenty of times where it comes in handy.

This feature works in a script file, but you will surely only use it in the interactive interpreter.

The Lone Underscore (_) works as a variable that stores the last result returned from the previous line of execution. It’s difficult to explain without the help of an example, which I’ll show here in a moment. In fact, I’m not having much luck finding more information about it on Google. Most of the results for “Underscore and Python”, talk about the traditional use of underscores to control namespace scoping. I’m not even positive if it’s a feature of the IDE environment, or the Python language itself. So far I’ve tried several IDE’s and this has worked in all of them, but your mileage may vary.

Example time

Here is one example showing how this feature works, it’s pretty trivial, but I think you can see how it might be useful.


For this example, I’m using matplotlib in pylab mode (interactively). This example shows how if you call a function, in this case figure(), and forget to capture the returned variable you can re-capture it using the underscore.

If you use the interactive intepretter fairly often, I think you can see how this might come in handy every now and then. If you find yourself needing to use this all the time, you might check out IPython (not to be confused with IronPython), and its history feature.