0

I want to concatenate every list in a list with the other list in list. This is what I want: given lists A and B that each have 2 lists inside it, I want to concatenate A[0]+B[0], A[0]+B[1], A[1]+B[0], A[1]+B[1]. I have written a simple code below:

def concatenate(seq1, seq2):
    for i in range(len(seq1)):
        for j in range(len(seq2)):
            return seq1[i] + seq2[j]

When I put [[1,2],[3,4]],[[2,3],[4,5]] as an argument, I want [[1,2,2,3], [1,2,4,5], [3,4,2,3], [3,4,4,5]] as a result but I'm only getting [1,2,2,3] at the moment. Is there a method to fix this?

rrr
  • 361
  • 4
  • 13
  • The cartesian product of `[[1,2],[3,4]]` with `[[2,3],[4,5]]` gives `([1, 2], [2, 3])`, `([1, 2], [4, 5])`, `([3, 4], [2, 3])`, `([3, 4], [4, 5])`. Then you just need to join the lists within each output pair. – Karl Knechtel Oct 16 '19 at 05:21

3 Answers3

1

You are currently returning the first result only. A return statement in any given function will return once, then exit the function. What is happening is that the moment your code gets there and concats two lists, it takes the first one and exits.

You need to do is return a list of all your results:

def concatenate(seq1, seq2):
    res = []
    for i in range(len(seq1)):
        for j in range(len(seq2)):
            res.append(seq1[i] + seq2[j])
    return res

This way you return one value containing all your lists.

anerisgreat
  • 342
  • 1
  • 7
1

anerisgreat's answer is correct! (that's why I voted it up as well)

I just wanted to add a simplification to the code, so that it looks "cleaner". Actually you don't need to iterate the for loop over the indices of the list, you can use the elements of the list directly!

def concatenate(seq1, seq2):
    res = []
    for i in seq1:
        for j in seq2:
            res.append(i + j)
    return res

Sorry, I would post this as a comment if I could, but I don't have enough reputation points!

Giallo
  • 96
  • 4
0

A list comprehension approach would be:

seq1 = [[1,2],[3,4]]
seq2 = [[2,3],[4,5]]

res = [(seq1[i] + seq2[j])  for i in range(len(seq1)) for j in range(len(seq2))]

res
> [[1, 2, 2, 3], [1, 2, 4, 5], [3, 4, 2, 3], [3, 4, 4, 5]]
Saurabh Jain
  • 1,600
  • 1
  • 20
  • 30