3

In Python 3.x, I'm calling a function rand_foo() which returns some random stuff each time being called. I wish to store the sequence of random results into a list. I'm using the following construct:

r = [ rand_foo() for i in range(10) ]

Now my PyCharm 3.0 IDE keeps warning: Local variable 'i' value is not used.

Is there an elegant way of removing the unnecessary variable? Indeed, in some cases, I could use itertools.repeat() or something like 10*[value], which, however, cannot be applied to my example above.

Tregoreg
  • 11,747
  • 12
  • 40
  • 63
  • 1
    I'd consider it to be a bug in PyCharm. It's very common for this type of expression to occur in Python code, and you shouldn't have to jump through hoops to avoid a silly warning. – John La Rooy Feb 18 '14 at 23:40

1 Answers1

11

The convention when a variable is unused is to use an underscore instead:

r = [rand_foo() for _ in range(10)]

See for example: Underscore _ as variable name in Python

I believe this will suppress your PyCharm warning

Community
  • 1
  • 1
mhlester
  • 21,143
  • 10
  • 49
  • 71
  • 2
    +1, but one warning: There are a few libraries, most notably the [`gettext`](http://docs.python.org/3/library/gettext.html) i18n module in the stdlib, that provide a special meaning for `_`, and if you use one of those, your linter (or a human reader) may complain that you're shadowing the global `_` with a local of the same name… (And, of course, if your expression is actually trying to _use_ `gettext`, you can't do this.) – abarnert Feb 18 '14 at 23:32
  • 1
    What a *terrible* choice that was! – mhlester Feb 18 '14 at 23:33
  • 1
    The Python `gettext` module is a wrapper around the C/Unix `gettext` library, which has been a de facto standard since the early 90s, and uses `_("string to localize")` to signal that the string should be localized. And perl, sh, Smalltalk, etc. bindings for `gettext` had already adopted the same `_` syntax. So there was really no choice… – abarnert Feb 18 '14 at 23:38
  • Correct, the warning disappeared! Thanks. – Tregoreg Feb 18 '14 at 23:38
  • Then, how to deal with the double loop? Something like `r=[[rand() for i in range(10)] for j in range(20)]` ? – wsysuper May 08 '15 at 12:40
  • 1
    @wsysuper if you don't care about the variable, you can actually reuse the underscore for both of them: `r=[[rand() for _ in range(10)] for _ in range(20)]` – mhlester May 08 '15 at 23:02