1

The code:

if (query_id, _) in hashtable[bucket]:

I expected this to work like in a for loop, but instead it gives this error:

NameError: global name '_' is not defined

hastable[bucket] is a list of pairs if that matters (which I doubt). Any ideas?

Bhargav Rao
  • 41,091
  • 27
  • 112
  • 129
gsamaras
  • 66,800
  • 33
  • 152
  • 256

3 Answers3

7

The x in y is not magic; it's basically the same as y.__contains__(x). Therefore, in cannot search with placeholders; the left argument is fully evaluated. Instead, use

if any(query_id == qid for (qid, _) in hashtable[bucket]):
phihag
  • 245,801
  • 63
  • 407
  • 443
  • OK that worked and I understood why my code failed. Can you please explain what you did? :) Moreover, do you think that my question is so bad to have a -1 score? :/ – gsamaras May 11 '16 at 09:28
  • `any` evaluates every element of its argument. The generator expression forming its argument yields True iff the first item matches `query_id`. – phihag May 11 '16 at 10:48
3

In a for loop (like the one you linked) the variable called _ is defined. As far as I can tell, you didn't define it anywhere. What did you expect _ to represent?

_ is just a normal variable name in Python, except in the interactive interpreter (where it represents the last variable output).

gsamaras
  • 66,800
  • 33
  • 152
  • 256
Matthias Schreiber
  • 1,632
  • 9
  • 19
1

In the concept where you use it only stores the last output variable. I'd go with:

if query_id in (x[0] for x in hashtable[bucket]):
armatita
  • 10,150
  • 6
  • 43
  • 44
ádi
  • 21
  • 4