Often when I’m using Python I’ll find myself writing list comprehensions that look something like this:
num_foobars = 10
foobars = [create_foobar() for idx in xrange(num_foobars)]
Obviously that works just fine, but it still feels a little awkward to me to creating a range and iterating dummy index across it, when I’m not actually using that information at all.
I’m not in any way concerned about performance or anything like that, it just doesn’t feel quite as wonderfully elegant as Python usually does.
I’m wondering if there’s any nice idiomatic way to avoid the unnecessary bits of list comprehension syntax, perhaps using something like map or something in itertools, to give me code that looks more like…
num_foobars = 10
foobars = repeat(create_foobar, num_foobars)
Here is the itertools way:
The itertools way is short and fast. That said, I prefer the list comprehension 🙂