Open In App

Python – Concatenate two list of lists Row-wise

Last Updated : 30 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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]]

Time Complexity: O(n*n)
Auxiliary Space: O(n)

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]]

The time and space complexity of both the methods is same:

Time Complexity: O(n2)

Space Complexity: O(n)

Method #3: Using extend()+loop

Python3




# Python3 code to demonstrate working of
# Concatenate 2 Matrix Row-wise
 
# 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 i in range(0, len(test_list1)):
    test_list1[i].extend(test_list2[i])
# 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]]

Time complexity: O(n*n), where n is the length of the test_list. The extend()+loop takes O(n*n) time
Auxiliary Space: O(n), extra space of size n is required

Method #4: Using numpy

Note: Install numpy module using command “pip install numpy”

Python3




#Importing numpy library
import numpy as np
 
#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))
 
#Using numpy to concatenate two lists row-wise
res = np.concatenate((test_list1, test_list2), axis = 1)
 
#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]]

Time Complexity: O(n^2)
Auxiliary Space: O(n)

Method #5: Using itertools.chain() and map()

This method uses the itertools.chain() function to chain the two input matrices, and the map() function to convert the chained iterable into a list of lists representing the concatenated matrix.

  • Import the itertools module.
  • Initialize the two matrices test_list1 and test_list2.
  • Use the zip() function to pair up corresponding rows of the two matrices.
  • For each pair of rows, use itertools.chain() to concatenate them row-wise.
  • Convert each concatenated row back into a list.
  • Collect all the concatenated rows into a new list, which represents the final concatenated matrix.

Python3




import itertools
 
# initializing lists
test_list1 = [[4, 3, 5, ], [1, 2, 3], [3, 7, 4]]
test_list2 = [[1, 3], [9, 3, 5, 7], [8]]
 
# using itertools.chain() and zip() to concatenate the two matrices row-wise
concatenated_matrix = [list(itertools.chain(*x)) for x in zip(test_list1, test_list2)]
 
# printing result
print("The concatenated Matrix : " + str(concatenated_matrix))


Output

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

Time complexity of the code is O(NM), where N is the number of lists in test_list1 and test_list2, and M is the maximum length of the lists.

The auxiliary space of the code is O(NM), since a new list of length N*M is created to store the concatenated matrix. 



Previous Article
Next Article

Similar Reads

Python | Concatenate two lists element-wise
Sometimes we come across this type of problem in which we require to leave each element of one list with the other. This type of problems usually occurs in developments in which we have the combined information, like names and surnames in different lists. Let's discuss certain ways in which this task can be performed. Method #1 : Using list compreh
4 min read
Python Program to Sort the matrix row-wise and column-wise
Given a n x n matrix. The problem is to sort the matrix row-wise and column wise.Examples: Input : mat[][] = { {4, 1, 3}, {9, 6, 8}, {5, 2, 7} } Output : 1 3 4 2 5 7 6 8 9 Input : mat[][] = { {12, 7, 1, 8}, {20, 9, 11, 2}, {15, 4, 5, 13}, {3, 18, 10, 6} } Output : 1 5 8 12 2 6 10 15 3 7 11 18 4 9 13 20 Approach: Following are the steps: Sort each r
4 min read
Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix
Find the number of negative numbers in a column-wise / row-wise sorted matrix M[][]. Suppose M has n rows and m columns. Example: Input: M = [-3, -2, -1, 1] [-2, 2, 3, 4] [4, 5, 7, 8] Output : 4 We have 4 negative numbers in this matrix We strongly recommend you to minimize your browser and try this yourself first. Naive Solution: Here's a naive, n
15+ min read
Python | Concatenate dictionary value lists
Sometimes, while working with dictionaries, we might have a problem in which we have lists as it's value and wish to have it cumulatively in single list by concatenation. This problem can occur in web development domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using sum() + values() This is the most recommended m
5 min read
Python program to concatenate every elements across lists
Given 2 lists, perform concatenations of all strings with each other across list. Input : test_list1 = ["gfg", "is", "best"], test_list2 = ["love", "CS"] Output : ['gfg love', 'gfg CS', 'is love', 'is CS', 'best love', 'best CS'] Explanation : All strings are coupled with one another. Input : test_list1 = ["gfg", "best"], test_list2 = ["love", "CS"
4 min read
Writing data from a Python List to CSV row-wise
Comma Separated Values (CSV) files a type of a plain text document in which tabular information is structured using a particular format. A CSV file is a bounded text format which uses a comma to separate values. The most common method to write data from a list to CSV file is the writerow() method of writer and DictWriter class. Example 1: Creating
2 min read
How to slice a PySpark dataframe in two row-wise dataframe?
In this article, we are going to learn how to slice a PySpark DataFrame into two row-wise. Slicing a DataFrame is getting a subset containing all rows from one index to another. Method 1: Using limit() and subtract() functions In this method, we first make a PySpark DataFrame with precoded data using createDataFrame(). We then use limit() function
4 min read
How to Zip two lists of lists in Python?
The normal zip function allows us the functionality to aggregate the values in a container. But sometimes, we have a requirement in which we require to have multiple lists and containing lists as index elements and we need to merge/zip them together. This is quite uncommon problem, but solution to it can still be handy. Let's discuss certain ways i
7 min read
Python - Reverse Row sort in Lists of List
Sometimes, while working with data, we can have a problem in which we need to perform the sorting of rows of the matrix in descending order. This kind of problem has its application in the web development and Data Science domain. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + sort() + reverse This problem ca
6 min read
Python | Program to count number of lists in a list of lists
Given a list of lists, write a Python program to count the number of lists contained within the list of lists. Examples: Input : [[1, 2, 3], [4, 5], [6, 7, 8, 9]] Output : 3 Input : [[1], ['Bob'], ['Delhi'], ['x', 'y']] Output : 4 Method #1 : Using len() C/C++ Code # Python3 program to Count number # of lists in a list of lists def countList(lst):
5 min read
Practice Tags :