Search code examples
python-3.xmatrix-multiplication

Python Lists Matrix Concatenation


Having 2 lists, can be different or same lengths.

a = [('1','1','2'), ('2','2','2','2'), ('3','3')]
b = [('7','8','8','9'), ('0','0','4','5')]

How can I add / concat the lists such that I'll get the following output.

Also, not sure if I'm using the right terminology here. Appreciate any corrections.

c = [
('1','1','2','7','8','8','9'),('1','1','2','0','0','4','5'),
('2','2','2','2','7','8','8','9'),('2','2','2','2','0','0','4','5'),
('3','3','7','8','8','9'),('3','3','0','0','4','5')
]

Essentially, c = [ (a[0] + b[0]), (a[0] + b[1]), (a[1] + b[0]), (a[1] + b[1]).....

Thus far, I've just been using for loops. I've looked at itertools.product, but the output isn't right. Additionally, if I increase it to 3 lists, then the combination becomes larger.


Solution

  • You were on the right track, thinking to use product.

    from itertools import product
    
    a = [('1','1','2','3','4','5','6'), ('2','2','2','2','2','2','2'), ('3','3','2','1','1','1','1')]
    b = [('7','8','8','9'), ('0','0','4','5')]
    
    paired_up = product(a, b)
    c = [sum(tuples, start=()) for tuples in x]  # The default start is 0, which leads to TypeErrors.
    
    print(c)
    # [('1', '1', '2', '3', '4', '5', '6', '7', '8', '8', '9'),
    #  ('1', '1', '2', '3', '4', '5', '6', '0', '0', '4', '5'),
    #  ('2', '2', '2', '2', '2', '2', '2', '7', '8', '8', '9'),
    #  ('2', '2', '2', '2', '2', '2', '2', '0', '0', '4', '5'),
    #  ('3', '3', '2', '1', '1', '1', '1', '7', '8', '8', '9'),
    #  ('3', '3', '2', '1', '1', '1', '1', '0', '0', '4', '5')]
    

    More than two lists? Pass them all to product.

    d = [('0',), ('1',)]  # Let's add another list to the mix.
    paired_up = product(a, b, d)  # It gets passed to `product` with the rest.
    c = [sum(tuples, start=()) for tuples in paired_up]
    print(c)
    # [('1', '1', '2', '3', '4', '5', '6', '7', '8', '8', '9', '0'),
    #  ('1', '1', '2', '3', '4', '5', '6', '7', '8', '8', '9', '1'),
    #  ('1', '1', '2', '3', '4', '5', '6', '0', '0', '4', '5', '0'),
    #  ('1', '1', '2', '3', '4', '5', '6', '0', '0', '4', '5', '1'),
    #  ('2', '2', '2', '2', '2', '2', '2', '7', '8', '8', '9', '0'),
    #  ('2', '2', '2', '2', '2', '2', '2', '7', '8', '8', '9', '1'),
    #  ('2', '2', '2', '2', '2', '2', '2', '0', '0', '4', '5', '0'),
    #  ('2', '2', '2', '2', '2', '2', '2', '0', '0', '4', '5', '1'),
    #  ('3', '3', '2', '1', '1', '1', '1', '7', '8', '8', '9', '0'),
    #  ('3', '3', '2', '1', '1', '1', '1', '7', '8', '8', '9', '1'),
    #  ('3', '3', '2', '1', '1', '1', '1', '0', '0', '4', '5', '0'),
    #  ('3', '3', '2', '1', '1', '1', '1', '0', '0', '4', '5', '1')]