Is there a more elegant way to write the following piece of Python?
[foo() for i in range(10)]
I want to accumulate the results of foo() in a list, but I don't need the iterator i.
Is there a more elegant way to write the following piece of Python?
[foo() for i in range(10)]
I want to accumulate the results of foo() in a list, but I don't need the iterator i.
One way to do this is to use _
:
[foo() for _ in range(10)]
This means exactly the same thing, but by convention the use of _
indicates to the reader that the index isn't actually used for anything.
Presumably foo()
returns something different every time you call it. If it doesn't, and it returns the same thing each time, then you can:
[foo()] * 10
to replicate the result of calling foo()
once, 10 times into a list.
By no means more elegant, but:
[x() for x in [foo]*10]
I think beyond that you have to go to Ruby ;)
map(lambda _ : foo(), range(10))
although this trades your problem with a meaningless iterator i with a new meaningless argument to the lambda expression.
map
would be nice if foo() took an argument, but it doesn't. So instead, create a dummy lambda that takes an integer argument, but just calls foo():
map(lambda i:foo(), range(10))
If you are on Python 3.x, map returns an iterator instead of a list - just construct a list with it:
list(map(lambda i:foo(), range(10)))