concept starmap in category data

appears as: starmap
Mastering Large Datasets with Python: Parallelize and Distribute Your Python Code

This is an excerpt from Manning's book Mastering Large Datasets with Python: Parallelize and Distribute Your Python Code.

  • starmap for parallel mapping over sequences of tuples
  • We can use the .imap method to work in parallel on very large sequences efficiently and starmap to work with complex iterables, especially those we’re likely to create using the zip function.

    Using starmap for working with zip in parallel

    We’ve seen how useful map can be for transforming data and how we can use it in parallel to speed up operations on large datasets; however, map has a disappointing shortcoming: it can only be used on functions that take a single parameter. Sometimes, this isn’t enough. We’ll want to use functions that take two or more parameters. We can use starmap in those situations to get the same benefits.

    The starmap function unpacks tuples as positional parameters to the function with which we’re mapping, and we can use it as a lazy function (from itertools.starmap) or a parallel function (as a method of a Pool() object, typically P.starmap). If we zip two sequences together, as we learned how to do in chapter 4, then we’ve got an iterable primed and ready to go for use with starmap.

    For example, we might want to find the largest element at each position in two sequences. Instead of looping through the sequences and comparing them, we could zip the sequences together and map over them. Listing 6.4 shows a comparison between these two methods. In the first, we use a list comprehension and an enumerate to compare the elements in the same places. In the second, with starmap, we zip together our parameters and then map the relevant function across them.

    Listing 6.4. Using starmap to use map with multiple variables
    from itertools import starmap                            #1
    xs = [7, 3, 1, 19, 11]                                   #2
    ys = [8, 1, -3, 14, 22]
    
    loop_maxes = [max(ys[i], x) for i,x in enumerate(xs)]    #3
    map_maxes = list(starmap(max, zip(xs, ys)))              #4
    
    print(loop_maxes)
    # [8, 3, 1, 19, 22]
    print(map_maxes)
    # [8, 3, 1, 19, 22]

    In addition to simplifying the code and bringing it into a pattern we’re familiar with by now, starmap brings along all the benefits we’ve grown to expect from map. Both zip and starmap are lazy, so we can work with big datasets with greater piece of mind that we’re only holding the data we need in memory. We can also quickly convert our starmap to work in parallel by making it a method call to a Pool() object.