0

I used a generator expression and then a list comprehension, what does '_' do here?

x = (i for i in [1, 2, 3])
[_ for i in x]

it gives such output

[]

[[], [], []]

[[[], [], []], [[], [], []], [[], [], []]]

[[[[], [], []], [[], [], []], [[], [], []]],
 [[[], [], []], [[], [], []], [[], [], []]],
 [[[], [], []], [[], [], []], [[], [], []]]]

on running two lines multiple times

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
apostofes
  • 2,959
  • 5
  • 16
  • 31

1 Answers1

3

If you're running the code at a Python REPL (which I think you are), then the underscore is a built-in variable that holds the last value calculated (and is updated by the REPL as values are calculated).

For example:

>>> x = 5   #  this is not _
>>> _ ** 2  #  so referencing it will raise a NameError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_' is not defined
>>> 5  #  the result of this will be the value referenced by _
5
>>> _ ** 2  #  now referencing it is okay
25
>>> _ ** 2  #  note that now the value of _ is 25 (the last value calculated)
625
>>>  #  and here its value is 625 (and so on)
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55