2

I have two lists, say firstList = ['a','b','c'] and secondList = [1,2,3,4].

I have to make a list of tuples by merging these lists in such a way that output should be like this

[('a',1),('a',2),('a',3),('a',4),('b',1), ('b',2) .....]

One simple way to do this is by

outputList = [] 
for i in firstList:
    for j in secondList:
        outputList.append((i,j))

How can I do this more simply?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Harshal
  • 117
  • 2
  • 10

1 Answers1

3
>>> firstList = ['a','b','c']
>>> secondList = [1,2,3,4]
>>> from itertools import product
>>> list(product(firstList, secondList))
[('a', 1), ('a', 2), ('a', 3), ('a', 4), ('b', 1), ('b', 2), ('b', 3), ('b', 4), ('c', 1), ('c', 2), ('c', 3), ('c', 4)]

Also here's a nicer version of your for loops using a list comprehension:

>>> [(i, j) for i in firstList for j in secondList]
[('a', 1), ('a', 2), ('a', 3), ('a', 4), ('b', 1), ('b', 2), ('b', 3), ('b', 4), ('c', 1), ('c', 2), ('c', 3), ('c', 4)]
jamylak
  • 128,818
  • 30
  • 231
  • 230
  • Great answer, +1. :) Just how I would have answered it (the list comprehension part) – Inbar Rose May 27 '13 at 13:50
  • This was what i was looking for..Thanks! which one will execute faster among these two ? – Harshal May 27 '13 at 13:51
  • @user1863122 I'd always go for `product`, it should be a tonne faster for huge lists but the the difference is negligible in smaller ones. – jamylak May 27 '13 at 13:54