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
  • 50,140
  • 28
  • 121
  • 140
gsamaras
  • 71,951
  • 46
  • 188
  • 305

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
  • 278,196
  • 72
  • 453
  • 469
  • 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
  • 71,951
  • 46
  • 188
  • 305
Matthias Schreiber
  • 2,347
  • 1
  • 13
  • 20
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
  • 12,825
  • 8
  • 48
  • 49
ádi
  • 31
  • 4