Reputation: 1646
Suppose I have two lists
L1 = [1,2,3]
and
L2 = [a,b,c]
Whats the fastest way to convert this to the list M = [(1,a),(2,b),(3,c)]
?
I tried M = [(x,y) for x in L1 for y in L2]
but this gives me all possible combination of elements. Sure I can write a loop to do it, but is there a more pythonic way to do this?
Upvotes: 3
Views: 1152
Reputation: 11866
Use zip()
.
This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence.
>> zip([1, 2, 3], ['a', 'b', 'c'])
[(1, 'a'), (2, 'b'), (3, 'c')]
Upvotes: 8