## 6.5 Grouping elements 

The last function I’ll discuss, itertools.groupby(iter, key_func=None) , is the most complicated. key_func(elem) is a function that can compute a key value for each element returned by the iterable. If you don’t supply a key function, the key is simply each element itself. 

groupby() collects all the consecutive elements from the underlying iterable that have the same key value, and returns a stream of 2-tuples containing a key value and an iterator for the elements with that key. 

city_list=[('Decatur','AL '), ( 'Huntsville','AL '), ( 'Selma','AL '), ('Anchorage','AK '), ( 'Nome ','AK '), ('Flagstaff','AZ '), ( 'Phoenix ','AZ '), ( 'Tucson','AZ '), ... ] def get_state(city_state): return city_state[1] itertools.groupby(city_list, get_state) => ('AL ', iterator-1), ('AK ', iterator-2), ('AZ ', iterator-3),... where iterator-1=> ('Decatur','AL '), ( 'Huntsville','AL '), ( 'Selma','AL ') iterator-2=> ('Anchorage','AK '), ( 'Nome ','AK ') iterator-3=> ('Flagstaff','AZ '), ( 'Phoenix ','AZ '), ( 'Tucson','AZ ') 

groupby() assumes that the underlying iterable’s contents will already be sorted based on the key. Note that the returned iterators also use the underlying iterable, so you have to consume the results of iterator-1 before requesting iterator-2 and its corresponding key. 

## 7 The functools module 

The$_{functools}$ module in Python 2.5 contains some higher-order functions. A higher-order function takes one or more functions as input and returns a new function. The most useful tool in this module is the$_{functools.}$ partial() function. 

For programs written in a functional style, you’ll sometimes want to construct variants of existing functions that have some of the parameters filled in. Consider a Python function$_{f(a, b, c)}$ ; you may wish to create a new function g(b, c) that’s equivalent to$_{f(1, b, c)}$ ; you’re filling in a value for one of$_{f()}$ ’s parameters. This is called “partial function application”. 

The constructor for $_{partial()}$takes the arguments (function, arg1, arg2, ..., kwarg1=value1, kwarg2=value2) . The resulting object is callable, so you can just call it to invoke $_{function}$with the filled-in arguments. 

Here’s a small but realistic example: 

import functools def log(message, subsystem): """Write the contents of 'message' to the specified subsystem.""" print(' %s : %s '%(subsystem, message)) ... server_log=functools .partial(log, subsystem ='server') server_log( 'Unable to open socket ') 

