I want this:
[foo() for _ in xrange (100)]
but beautifuller. ?
I want this:
[foo() for _ in xrange (100)]
but beautifuller. ?
You can write a generator repeat
like this:
def repeat(times, func, *args, **kwargs):
for _ in xrange(times):
yield func(*args, **kwargs)
Then:
list(repeat(100, foo))
It also accepts arguments to be passed on to the function, so you can:
from random import randint
list(repeat(100, randint, 1, 100)) # 100 random ints between 1 and 100
Since it's a generator, you can pipe it into any kind of iterable, be it a list
(as here) or a tuple
or a set
, or use it in a comprehension or a loop.
I'm afraid you're not gonna get it any prettier than that in Python, except that some people would advise against _
for an "anonymous" variable. This is the Pythonic idiom for doing what you want.
(The _
can be considered confusing to novices because it can be mistaken for special syntax. I use it, but only in the "expert parts" of my code. I also encounter it more and more often, but opinion still seems a bit divided on this one.)
Depending on your definition of "beautifuller", you may prefer this:
map(lambda x: foo(), xrange(100))
Although what you have already is much nicer IMO.
Depending on what it does, you can make foo()
a generator.
Your list comprehension is already beatiful and effective but if you need several options to do the same things then i think you can use map here. In case you need to call a certain function the specified number of times use:
# in case your func looks like
def func():
# do something
#then
map(func(), xrange(numberOfTimes))
In case your function need value from range then you can use map with lambda:
# in case your func looks like
def func(value):
# do something with value
#then
map(lambda val: func(val), xrange(numberOfTimes))
Or in case you need to use data from several lists of the same length:
# in case your func looks like
def func(value1, value2):
# do something with values
#then
map(lambda val: func(*val), zip(xrange(10), xrange(10,20)))
And so on...
In case foo()
always returns the same result, you could use
[foo()]*100
This has the advantage that foo()
is only called once.
Edit: As @larsmans points out this only makes sense though if foo()
returns an immutable result.
In all other cases, your solution is fine!