Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Omit iterator in list comprehension?

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.

like image 838
oceanhug Avatar asked Nov 06 '22 08:11

oceanhug


1 Answers

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.

like image 144
Greg Hewgill Avatar answered Nov 11 '22 06:11

Greg Hewgill