2

I have already checked this post How to merge lists into a list of tuples in Python? but it doesn't seem to fit to my issue.

I want to merge multiple lists together to get a tuple for each multiplication. So let's say:

listA = ['a', 'b', 'c', 'd']
listB = [ 1 ,  2 ,  3 ,  4 , 5 ]
listC = ['!', '?', '=']

The lists do not have the same length. My desired result would be:

result = [('a', 1, '!'), ('a', 1, '?'),  ('a', 1, '='),  ('a', 2, '!')...

As far as I got it, the zip() functions only joins two elements to a list together with the same index which is not what I want.

Community
  • 1
  • 1
Calanas
  • 33
  • 1
  • 4

1 Answers1

2

Use itertools.product:

>>> listA = ['a', 'b', 'c', 'd']
>>> listB = [ 1 ,  2 ,  3 ,  4 , 5 ]
>>> listC = ['!', '?', '=']
>>> result = list(itertools.product(listA, listB, listC))
>>> result[:5]
[('a', 1, '!'), ('a', 1, '?'), ('a', 1, '='), ('a', 2, '!'), ('a', 2, '?')]
>>> 
falsetru
  • 357,413
  • 63
  • 732
  • 636