Which is more pythonic?
python at mrabarnett.plus.com
Fri Dec 4 01:52:31 CET 2009
Filip Gruszczyński 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:
> But I could also do:
> map(self.__choices, choicesBox.addItem)
> [choicesBox.addItem(choice) for choice in self.__choices]
> I guess map version would be fastest and explicit for is the slowest
> version. 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?
Is .addItem() a function (returns a result) or a procedure (called
for its side-effect, ie adding an item to a collection)?
It's a procedure, so the first form is Pythonic.
If it was a function then the third form would be Pythonic.
The second form is what you would've done before list comprehensions
More information about the Python-list