ThorSummoner
ThorSummoner

Reputation: 18149

Python Multiply tuples of equal length

I was hoping for an elegant or effective way to multiply sequences of integers (or floats).

My first thought was to try (1, 2, 3) * (1, 2, 2) would result (1, 4, 6), the products of the individual multiplications.

Though python isn't preset to do that for sequences. Which is fine, I wouldn't really expect it to. So what's the pythonic way to multiply (or possibly other arithmetic operations as well) each item in two series with and to their respective indices?

A second example (0.6, 3.5) * (4, 4) = (2.4, 14)

Upvotes: 9

Views: 8364

Answers (5)

Victor Castillo Torres
Victor Castillo Torres

Reputation: 10811

A simpler way would be:

from operator import mul

In [19]: tuple(map(mul, [0, 1, 2, 3], [10, 20, 30, 40]))
Out[19]: (0, 20, 60, 120)

Upvotes: 7

thefourtheye
thefourtheye

Reputation: 239573

The simplest way is to use zip function, with a generator expression, like this

tuple(l * r for l, r in zip(left, right))

For example,

>>> tuple(l * r for l, r in zip((1, 2, 3), (1, 2, 3)))
(1, 4, 9)
>>> tuple(l * r for l, r in zip((0.6, 3.5), (4, 4)))
(2.4, 14.0)

In Python 2.x, zip returns a list of tuples. If you want to avoid creating the temporary list, you can use itertools.izip, like this

>>> from itertools import izip
>>> tuple(l * r for l, r in izip((1, 2, 3), (1, 2, 3)))
(1, 4, 9)
>>> tuple(l * r for l, r in izip((0.6, 3.5), (4, 4)))
(2.4, 14.0)

You can read more about the differences between zip and itertools.izip in this question.

Upvotes: 8

Warren Weckesser
Warren Weckesser

Reputation: 114911

If you are interested in element-wise multiplication, you'll probably find that many other element-wise mathematical operations are also useful. If that is the case, consider using the numpy library.

For example:

>>> import numpy as np
>>> x = np.array([1, 2, 3])
>>> y = np.array([1, 2, 2])
>>> x * y
array([1, 4, 6])
>>> x + y
array([2, 4, 5])

Upvotes: 6

desired login
desired login

Reputation: 1190

A = (1, 2, 3)
B = (4, 5, 6)    
AB = [a * b for a, b in zip(A, B)]

use itertools.izip instead of zip for larger inputs.

Upvotes: 1

ThorSummoner
ThorSummoner

Reputation: 18149

With list comprehensions the operation could be completed like

def seqMul(left, right):
    return tuple([value*right[idx] for idx, value in enumerate(left)])

seqMul((0.6, 3.5), (4, 4))

Upvotes: 1

Related Questions