treyhunner,
@treyhunner@mastodon.social avatar

Python tip 💡

If you just ran an expression in the REPL and you'd like to capture its value into a variable, you don't need to run it again!

You can use the _ variable to get the value of the last REPL output!

You'll also sometimes see _ used as a throwaway variable:

>>> from random import randint
>>> numbers = [randint(1, 5) for _ in range(10)]

_ works in the built-in Python REPL and pretty much all third-party REPLs.

Try _ out yourself in a REPL: https://pym.dev/repl

random.randint used in a list comprehension to generate a range with _ used as a throwaway variable. See code at https://pym.dev/p/3328x

moshez,
@moshez@mastodon.social avatar

@treyhunner Even better, in IPython and Jupyter, _<idx> will retrieve any value, so nothing in the repl needs to be recomputed:

image/png

  • All
  • Subscribed
  • Moderated
  • Favorites
  • python
  • DreamBathrooms
  • mdbf
  • ethstaker
  • magazineikmin
  • cubers
  • rosin
  • thenastyranch
  • Youngstown
  • osvaldo12
  • slotface
  • khanakhh
  • kavyap
  • InstantRegret
  • Durango
  • JUstTest
  • everett
  • tacticalgear
  • modclub
  • anitta
  • cisconetworking
  • tester
  • ngwrru68w68
  • GTA5RPClips
  • normalnudes
  • megavids
  • Leos
  • provamag3
  • lostlight
  • All magazines