Multiply number list by range of numbers
<p>I'm trying to write code for a modulus 11 but I'm failing to make it more python-like.</p>

<p>As of now I'm using a weight and increasing it, checking when it reaches a number and then set it to it's original value.</p>

<p>Let's say I have a list of numbers
<code>1..20</code> and I'd like to multiply them by <code>2,3,4,5,6,7,8,9,2,3,4,etc</code> so that each index would be multiplied by an increasing number.</p>

<p>1x2, 2x3, 3x4, 4x5, 5x6, 6x7, 7x8, 8x9, 9x2, 10x3, etc..</p>

<p>Is there an elegant way to do this?</p>

<p>Unelegant way:</p>

<pre><code>def mod11(list, max_weight=9):
    sum = 0
    weight = 2

    for item in reversed(list):
        sum += item * weight
        weight += 1

        if weight &gt; max_weight:
            weight = 2

    mod = 11 - sum % 11

    if mod &gt; 9:
        return 0

    else:
        return mod
</code></pre>

<p>You can use <a href="https://docs.python.org/2/library/itertools.html#itertools.starmap" rel="nofollow">starmap</a> and <a href="https://docs.python.org/2/library/itertools.html#itertools.cycle" rel="nofollow">cycle</a> from itertools.</p>

<p>First create a list of tuples to multiply together:</p>

<pre><code>&gt;&gt;&gt; from itertools import starmap, cycle
&gt;&gt;&gt; li=zip(range(1,21), cycle(range(2,10)))
&gt;&gt;&gt; li
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 2), (10, 3), (11, 4), (12, 5), (13, 6), (14, 7), (15, 8), (16, 9), (17, 2), (18, 3), (19, 4), (20, 5)]
</code></pre>

<p>Then use <code>starmap</code> and <code>mul</code> (from operator) to multiply:</p>

<pre><code>&gt;&gt;&gt; from operator import mul 
&gt;&gt;&gt; list(starmap(mul, li))
[2, 6, 12, 20, 30, 42, 56, 72, 18, 30, 44, 60, 78, 98, 120, 144, 34, 54, 76, 100]
</code></pre>

<p>If you wanted a straight comprehension, you can do:</p>

<pre><code>&gt;&gt;&gt; [x*y for x, y in ((e+1, (e%8)+2) for e in range(20))]
[2, 6, 12, 20, 30, 42, 56, 72, 18, 30, 44, 60, 78, 98, 120, 144, 34, 54, 76, 100]
</code></pre>

python