Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python – Concatenate two list of lists Row-wise

  • Difficulty Level : Basic
  • Last Updated : 03 Aug, 2021

Given two matrices, the task is to write a Python program to add elements to each row from initial matrix.

Input : test_list1 = [[4, 3, 5,], [1, 2, 3], [3, 7, 4]], test_list2 = [[1, 3], [9, 3, 5, 7], [8]]

Output : [[4, 3, 5, 1, 3], [1, 2, 3, 9, 3, 5, 7], [3, 7, 4, 8]]

Explanation : Matrix is row wise merged.

Input : test_list1 = [[4, 3, 5,], [1, 2, 3], [3, 7, 4]], test_list2 = [[1], [9], [8]]

Output : [[4, 3, 5, 1], [1, 2, 3, 9], [3, 7, 4, 8]]

Explanation : Matrix is row wise merged.

Method #1 : Using enumerate() + loop

In this, we get each index of each initial matrix and append its all elements to the second matrix’s corresponding row.

Python3




# Python3 code to demonstrate working of
# Concatenate 2 Matrix Row-wise
# Using loop + enumerate()
  
# initializing lists
test_list1 = [[4, 3, 5, ], [1, 2, 3], [3, 7, 4]]
test_list2 = [[1, 3], [9, 3, 5, 7], [8]]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
for idx, ele in enumerate(test_list1):
    new_vals = []
  
    # getting all values at same index row
    for ele in test_list2[idx]:
        new_vals.append(ele)
  
    # extending the initial matrix
    test_list1[idx].extend(new_vals)
  
# printing result
print("The concatenated Matrix : " + str(test_list1))

Output:

The original list 1 is : [[4, 3, 5], [1, 2, 3], [3, 7, 4]]

The original list 2 is : [[1, 3], [9, 3, 5, 7], [8]]

The concatenated Matrix : [[4, 3, 5, 1, 3], [1, 2, 3, 9, 3, 5, 7], [3, 7, 4, 8]]

Method #2 : Using zip() + list comprehension

In this, we perform the task of concatenating rows using zip(), and iteration through each row happens using list comprehension.

Python3




# Python3 code to demonstrate working of
# Concatenate 2 Matrix Row-wise
# Using zip() + list comprehension
  
# initializing lists
test_list1 = [[4, 3, 5, ], [1, 2, 3], [3, 7, 4]]
test_list2 = [[1, 3], [9, 3, 5, 7], [8]]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# zip() combines the results
# list comprehension provides shorthand
res = list(sub1 + sub2 for sub1, sub2 in zip(test_list1, test_list2))
  
# printing result
print("The concatenated Matrix : " + str(res))

Output:

The original list 1 is : [[4, 3, 5], [1, 2, 3], [3, 7, 4]]

The original list 2 is : [[1, 3], [9, 3, 5, 7], [8]]

The concatenated Matrix : [[4, 3, 5, 1, 3], [1, 2, 3, 9, 3, 5, 7], [3, 7, 4, 8]]


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!