Universal Functions (ufuncs)

Numeric supplies named functions with the same semantics as Python’s arithmetic, comparison, and bitwise operators. Similar semantics (element-wise operation, broadcasting, coercion) are also available with other mathematical functions, both binary and unary, that Numeric supplies. For example, Numeric supplies typical mathematical functions similar to those supplied by built-in module math, such as sin, cos, log, and exp.

These functions are objects of type ufunc (which stands for universal function) and share several traits in addition to those they have in common with array operators. Every ufunc instance u is callable, is applicable to sequences as well as to arrays, and lets you specify an optional output argument. If u is binary (i.e., if u accepts two operand arguments), u also has four callable attributes, named u .accumulate, u .outer, u .reduce, and u .reduceat. The ufunc objects supplied by Numeric apply only to arrays with numeric type codes (i.e., not to arrays with type code 'O' or 'c').

Any ufunc u applies to sequences, not just to arrays. When you start with a list L, it’s faster to call u directly on L rather than to convert L to an array. u’s return value is an array a; you can perform further computation, if any, on a, and then, if you need a list result, you can convert the resulting array to a list by calling its method tolist. For example, say you must compute the logarithm of each item of a list and return another list. On my ...

Get Python in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.