Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "_" not always give me the last result in interactive shell

Generally I use _ to access the last result in the Python interactive shell. Especially to quickly assign a variable to a result I think might be important later.

What I discovered recently though was if I use the _ as a value in a for loop that I can no longer use _ to reference the last result.

Example:

>>> for _ in range(10):
...   pass
...
>>> 120
120
>>> a=_
>>> a
9
>>> _
9
>>> del _ # Now I can use _ to reference the last result again
>>> 120
120
>>> a=_
>>> a
120

If I use a blank for loop then _ isn't able to be considered the last result until I delete it, and then it works.

If I list comprehension though it seems to still work fine:

>>> [1 for _ in range(10)]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
>>> 120
120
>>> a=_
>>> a
120    

So I guess my question is why? Why does this happen? Why is it that _ can sometimes be changed so that it doesn't mean last result?

like image 514
Chrispresso Avatar asked Jul 30 '18 20:07

Chrispresso


1 Answers

The reason is pretty simple- try doing

[i for i in range(1000)]

and then accessing i- you'll see that i isn't defined (it's scope is within the list comprehension- when you exit the list comprehension, there "is no i").

This is in contrast to a for loop, where the scope of i is NOT within the actual for loop- so you can access it from outside.

So if we go to your case (with the _), if the _ is defined, like with a regular for loop, then you need to del it. If you do it within a list comprehension, once the list comprehension is over, the underscore is no longer defined- which means it'll just be the last value

like image 184
maor10 Avatar answered Sep 30 '22 18:09

maor10