On Wed, Oct 01, 2014 at 01:58:16AM +0100, Alan Gauld wrote: > On 30/09/14 23:54, Clayton Kirkwood wrote: > >I don't understand the multiplicity of some tools. Namely, why is there a > >'a+b', operator.add(a,b), operator.__add__(a,b), operator.iadd(a,b), > >operator.__iadd__(a,b) and their related operators? > > The operator module is there largely to allow you to pass > operations to functions that take functions as parameters. > For example map() which applies a function to a collection. > > total = map(operator.add, [1,2,3,4,5,6]) > > is the same result as > > total = sum([1,2,3,4,5,6])
No, you're thinking of reduce(), not map(). reduce() takes a function and applies it all of the items, pairwise, gradually reducing the result down to a single value. map() takes a function and applies it to each of the items individually, returning a new list. [...] > The operator module has functions representing most > of the builtin operations in Python. > > I'm not really sure why it implements the dunder methods > (eg operatotor.__add__()) corresponding to the operations though. > I'm sure somebody else can provide a good explanation... They're just aliases. According to the documentation, the "official" versions are operator.__add__, etc. with the underscore-less versions just given for convenience. But in practice everybody uses the non-underscore versions. My advice is to ignore the operator.__add__ and similar double-underscore versions. They're longer to type, don't add any additional value, and in fact are actually misleading since they don't directly call the dunder methods. -- Steven _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor