On Thu, 03 Dec 2009 15:41:56 -0000, Filip GruszczyƄski <grusz...@gmail.com> wrote:

I have just written a very small snippet of code and started thinking,
which version would be more pythonic. Basically, I am adding a list of
string to combo box in qt. So, the most obvious way is:

for choice in self.__choices:
        choicesBox.addItem(choice)

But I could also do:

map(self.__choices, choicesBox.addItem)

or

[choicesBox.addItem(choice) for choice in self.__choices]

I guess map version would be fastest and explicit for is the slowest
version.

I vaguely recall someone (Steven?) doing some timings that came up with the opposite answer. The list comprehension is probably the worst performing, since it creates a whole new list of the return values of choicesBox.addItem(choice), then throws it away.

However, the first, most obvious way seems most clear to me
and I don't have to care about speed with adding elements to combo
box. Still, it's two lines instead of one, so maybe it's not the best.
So, which one is?

Your instincts are right, the explicit for loop is the more pythonic way in this case. More efficient or not, map() isn't a particularly pythonic way to do things, and there's no point using a list comprehension when you aren't building a list.

--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to