Python - Concatenate two list of lists Row-wise

Python - Concatenate two list of lists Row-wise

In this tutorial, we will learn how to concatenate two lists of lists (matrices) row-wise.

Objective:

Given two lists of lists, listA and listB, we aim to concatenate them such that each row of listA is appended with the corresponding row from listB.

For example: If listA = [[1, 2], [3, 4]] and listB = [[5, 6], [7, 8]], the result should be [[1, 2, 5, 6], [3, 4, 7, 8]].

Steps:

  1. Initialize the Result List: Create an empty list that will store the concatenated rows.
  2. Iterate Over Lists: Use a loop or a list comprehension to go through both lists and concatenate corresponding rows.
  3. Append to the Result List: For each iteration, append the concatenated row to the result list.
  4. Return the Result List.

Using a Basic Loop:

def concatenate_rowwise(listA, listB): result = [] for rowA, rowB in zip(listA, listB): result.append(rowA + rowB) return result # Test listA = [[1, 2], [3, 4]] listB = [[5, 6], [7, 8]] print(concatenate_rowwise(listA, listB)) # [[1, 2, 5, 6], [3, 4, 7, 8]] 

Using List Comprehension:

This approach provides a more concise method using list comprehension:

def concatenate_rowwise(listA, listB): return [rowA + rowB for rowA, rowB in zip(listA, listB)] # Test listA = [[1, 2], [3, 4]] listB = [[5, 6], [7, 8]] print(concatenate_rowwise(listA, listB)) # [[1, 2, 5, 6], [3, 4, 7, 8]] 

Explanation:

  • The zip() function is utilized to pair up each row of listA with the corresponding row from listB.

  • For every paired-up row, we concatenate the rows using the + operator.

  • This concatenated list is then either appended to the result list (in the loop method) or directly created as part of the new list (in the list comprehension method).

Tips:

  • This method assumes that listA and listB have the same number of rows. If they might have a different number of rows and you want to handle such cases gracefully, you should implement additional logic or error-checking.

With this tutorial, you now understand how to concatenate two lists of lists row-wise in Python.


More Tags

knex.js in-place sql-server-2014-express react-redux html-table ejb-3.0 apache-commons-httpclient jacoco-maven-plugin jsse google-drive-api

More Programming Guides

Other Guides

More Programming Examples