0

I am new to python and constantly use REPL to check some code snippets.

I was trying to check if a set contains a tuple, based only on the first value in the tuple. Knowing that _ in python means pass, I wrote something like this:

Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> x = {('a',1),('b',2)}
>>> x
{('b', 2), ('a', 1)}
>>> ('a',_) in x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>> ('a',1) in x
True
>>> ('a',_) in x
True

So as you can see the first ('a',_) in x statement resulted in a TypeError, but the next one gave an output without an error.

Can someone please explain what happened here?

ak92
  • 41
  • 9
  • "Knowing that `_` in python means `pass`,' *it does not mean `pass`*. `_` is just a normal variable name, like `foo` or `x`. In the REPL, it is assigned the *last* output. In Python code, it is *conventionally* used as a name for a throw-away variable, like to make a list of ten 1s, `[1 for _ in range(10)]` – juanpa.arrivillaga Oct 06 '18 at 19:36

1 Answers1

0

_ is set to the last non-None result returned by the repl. Thus >>> ('a',_) in x is the same as >>> ('a', True) in x. Note also that True is a special case of 1 in Python.

gilch
  • 10,813
  • 1
  • 23
  • 28