# Doing calculation in Tuples on List Comprehension

0 votes
1 view

I am new to list comprehension, and I'd like to do something with tuples. So this is the problem:

Given two vectors l1 and l2, I wish to combine them into tuples. Then I'd like to multiply them before summing all of them up.

So for example, if i have l1 = [1,2,3] and l2 = [4,5,6], I'd like to combine them with zip function into [(1,4),(2,5),(3,6)].

After this, I want to multiply and add 1 to the tuples. So it will be [(1*4)+1,(2*5)+1,(3*5)+1], giving [4,11,16]

After that I want to sum the list up into 4+11+16 which should give 31.

I've learnt tuple(map(operator.add, a, b)) before which can add up the tupples. But since now I need to do one more calculation, I have no idea how to get started. It will be good if it can be done in a single line with list comprehension. Anyone got an idea?

## 1 Answer

0 votes
by (41.4k points)

Let’s Consider:

sum(a * b + 1 for a, b in zip(l1, l2))

Now

>>> l1 = [1,2,3]; l2 = [4,5,6]

>>> sum(a * b + 1 for a, b in zip(l1, l2))

This will give the output:

35

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer