1

In my code I'm currently doing something like this:

for _ in xrange(n):
    f(x)

where f is some arbitrary function that does not return anything (ie just a None) and x is an arbitrary input for this function

I was just wondering whether there is a proper way to do this in one line? There are a lot of functions in python like map, fold, etc that are used to operate on elements of a list, but all of them seem to consider that we are interested in what the function returns.

Doing:

[f(x) for _ in xrange(n)]

is actually working fine, but it returns a whole list of None that I don't need.

dhokas
  • 1,771
  • 2
  • 13
  • 22
  • Since the price of `\n` characters is still 0, it's OK to do this in 2 lines. – wim Nov 08 '16 at 22:46
  • 1
    The second one should be avoided because you are using the comprehension for its side-effect, which is a huge [no-no](http://stackoverflow.com/questions/5753597/is-it-pythonic-to-use-list-comprehensions-for-just-side-effects) – idjaw Nov 08 '16 at 22:54

2 Answers2

3

two lines is fine and expected.

You could do for _ in range(n): f(x) if you had a good reason, but you probably don't have one of those.

Wayne Werner
  • 49,299
  • 29
  • 200
  • 290
0

For me, writing something like

for i in array: f(x)

works in python 2.7 and 3

pokeyOne
  • 312
  • 1
  • 2
  • 12