conditional product in numpy
Question: I have a list which controls what terms in the data list have to be multiplied

    
    
    control_list = [1, 0, 1, 1, 0]
    data_list = [5, 4, 5, 5, 4]
    

I need to find product of elements in the `data_list` for which the
`control_list` has `1`. My current attempt is naive and looks ugly!

    
    
    product = 1
    for i in range(len(control_list)):
        if control_list[i]: 
            product *= data_list[i]
    

I looked at `numpy.where()` to get the required elements in `data_list` but it
looks like I did not get it right:

    
    
    numpy.where(control_list, data_list)
    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    <ipython-input-12-1534a6838544> in <module>()
    ----> 1 numpy.where(control_list, data_list)
    
    ValueError: either both or neither of x and y should be given
    

My question is, can I do this somehow using numpy more efficiently?


Answer: Try this out. You can convert control_list to a list of booleans, and then use
it to index into data_list. Then, you can use numpy's product function to get
the product of all of the values.

    
    
    >>> import numpy as np
    >>> cList = np.array(control_list, dtype=np.bool)
    >>> cList
    array([ True, False,  True,  True, False], dtype=bool)
    >>> data_list = np.array(data_list)
    >>> data_list[cList] # numpy supports fancy indexing
    array([5, 5, 5])
    >>> np.product(data_list[cList])
    125
    

