Itertools question: how to call a function n times?

jrbj john.jusayan at gmail.com
Thu Jul 19 18:25:19 EDT 2007


On Jul 19, 8:35 am, Matthew Wilson <m... at tplus1.com> wrote:
> I want to write a function that each time it gets called, it returns a
> random choice of 1 to 5 words from a list of words.
>
> I can write this easily using for loops and random.choice(wordlist) and
> random.randint(1, 5).
>
> But I want to know how to do this using itertools, since I don't like
> manually doing stuff like:
>
>     phrase = list()
>     for i in random.randint(1, 5):
>
>         phrase.append(random.choice(wordlist))

All the previous suggestions in this thread are good. If you *must*
use itertools, you can use the itertools.repeat function to return an
object x many times:

phrase = [somewords(wordlist) for somewords in
              itertools.repeat(random.choice, random.randint(1, 5))]


Hope it helps,
John




More information about the Python-list mailing list