Which is more pythonic?

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Fri Dec 4 06:26:58 EST 2009


Filip Gruszczyński a écrit :
> 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)

this should actually be
   map(choicesBox.addItem, self.__choices)

!-)

> or
> 
> [choicesBox.addItem(choice) for choice in self.__choices]
> 
> I guess map version would be fastest and explicit for is the slowest
> version. 

I don't think so - there's at least the overhead of creating a useless 
list. But if you're after micro-optimization, there's an obvious one :

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

Attribute lookup can be costly, specially when the attribute is a method.

Now unless you have a _very_ big choices list - which is probably not 
the case - the gain will still be marginal.

> However, the first, most obvious way seems most clear to me

It is.

> 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?

The first, obviously - and I'm the kind of guy that really dig obscure 
one-liners !-)



More information about the Python-list mailing list