user1710165
user1710165

Reputation: 63

List Comprehension in Python

Let's say I have a list of tuples:

a = [(1, 2), (3, 4), (4, 5)]

and another list, no tuples:

b = [1, 2, 3]

How would I use list comprehension to multiply only the first value of each tuple in a by each respective value in b? That is, [a[0][0] * b[0], a[1][0] * b[1], a[2][0] * b[2]] (Should equal [1, 6, 12])

Upvotes: 1

Views: 110

Answers (3)

Jon
Jon

Reputation: 12874

For giant lists you better use izip from itertools as you don't need to create a new list before iterating over it: http://pymotw.com/2/itertools/#producing-new-values. A huge advantage of this methodology is that you are not limited to sequences. You can use generators as well.

import itertools as it

a = [1,2,3,4,5]
b = [6,7,8,9,10]

for e in it.izip(a,b):
    print e

This prints the tuples:

(1, 6)
(2, 7)
(3, 8)
(4, 9)
(5, 10)

Upvotes: 0

BrenBarn
BrenBarn

Reputation: 251383

>>> a = [(1, 2), (3, 4), (4, 5)]
... b = [1, 2, 3]
>>> [x[0]*y for x, y in zip(a, b)]
[1, 6, 12]

The zip function is the key.

Upvotes: 4

user711413
user711413

Reputation: 777

For instance, you can use [a[0]*b for a,b in zip(a,b)]

The zip function creates a list of tuples. The list is as long as the shortest list of arguments to zip, and the ith element of each tuple comes from the ith argument of zip.

>>> c = [1, 2, 3]
>>> d = [4, 5, 6]
>>> zip(c,d)
[(1, 4), (2, 5), (3, 6)]

Upvotes: 1

Related Questions