0

I have several sampling functions that need to be called for a certain amount of times as in the following instruction:

samples = [do_sampling() for _unused in range(n_samples)]

I wonder, is there a more compact way to express that statement, especially by avoiding the _unused variable?

Will
  • 24,082
  • 14
  • 97
  • 108
fstab
  • 4,801
  • 8
  • 34
  • 66
  • Are you building a list, or are you using the list comprehension syntax as a means to loop? Why the need to be more compact? Why not *more readable for future maintainers*? – Martijn Pieters May 16 '15 at 09:14
  • See [Side-effects in python map (python "do" block)](https://stackoverflow.com/q/14447560) and [How (in)efficient is a list comprehension if you don't assign it?](https://stackoverflow.com/q/21428602) for discussions on the latter use. – Martijn Pieters May 16 '15 at 09:14
  • @MartijnPieters: it's just a list built by sampling a number of times independently, with no side effects and no parameters to the sampling function. Any suggestion on how to make it more readable is well accepted. – fstab May 16 '15 at 09:18
  • 1
    You have it as readable as it gets. I use `_` for the loop variable. – Martijn Pieters May 16 '15 at 09:18

2 Answers2

2

If your goal is to build a list from the do_sampling() return values, there is no more compact syntax.

The Python convention is to use _ for the I'm ignoring this variables:

samples = [do_sampling() for _ in range(n_samples)]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

There's not a better way to do this that I'm aware of. The convention is to do this:

samples = [do_sampling() for _ in range(n_samples)]

If you're using Python 2.x and not Python 3.x, you can gain a performance improvement by using a generator-version of range, xrange(), rather than range():

samples = [do_sampling() for _ in xrange(n_samples)]

The _ variable is typically used as Pythonic notation for a discarded, unused variable.

Will
  • 24,082
  • 14
  • 97
  • 108