Open In App

Python - Vertical Concatenation in Matrix

Last Updated : 24 Mar, 2023
Suggest changes
Share
Like Article
Like
Report

Given a String Matrix, perform column-wise concatenation of strings, handling variable lists lengths.

Input : [["Gfg", "good"], ["is", "for"]] 
Output : ['Gfgis', 'goodfor'] 
Explanation : Column wise concatenated Strings, "Gfg" concatenated with "is", and so on. 

Input : [["Gfg", "good", "geeks"], ["is", "for", "best"]] 
Output : ['Gfgis', 'goodfor', "geeksbest"] 
Explanation : Column wise concatenated Strings, "Gfg" concatenated with "is", and so on.

Method #1: Using loop

This is brute way in which this task can be performed. In this, we iterate for all the columns and perform concatenation. 

Python3
# Python3 code to demonstrate working of  # Vertical Concatenation in Matrix # Using loop # initializing lists test_list = [["Gfg", "good"], ["is", "for"], ["Best"]] # printing original list print("The original list : " + str(test_list)) # using loop for iteration res = [] N = 0 while N != len(test_list): temp = '' for idx in test_list: # checking for valid index / column try: temp = temp + idx[N] except IndexError: pass res.append(temp) N = N + 1 res = [ele for ele in res if ele] # printing result  print("List after column Concatenation : " + str(res)) 

Output
The original list : [['Gfg', 'good'], ['is', 'for'], ['Best']] List after column Concatenation : ['GfgisBest', 'goodfor']

Time Complexity: O(n2)
Space Complexity: O(n)

Method #2 : Using join() + list comprehension + zip_longest()

The combination of above functions can be used to solve this problem. In this, we handle the null index values using zip_longest, and join() is used to perform task of concatenation. The list comprehension drives one-liner logic.

Python3
# Python3 code to demonstrate working of  # Vertical Concatenation in Matrix # Using join() + list comprehension + zip_longest() from itertools import zip_longest # initializing lists test_list = [["Gfg", "good"], ["is", "for"], ["Best"]] # printing original list print("The original list : " + str(test_list)) # using join to concaternate, zip_longest filling values using  # "fill" res = ["".join(ele) for ele in zip_longest(*test_list, fillvalue ="")] # printing result  print("List after column Concatenation : " + str(res)) 

Output
The original list : [['Gfg', 'good'], ['is', 'for'], ['Best']] List after column Concatenation : ['GfgisBest', 'goodfor']

Time Complexity: O(n2) -> (loop+join)
Space Complexity: O(n)

Method #3: Using numpy.transpose() and numpy.ravel()

Step-by-step approach:

  • Import the numpy library.
  • Initialize the list.
  • Find the maximum length of a sublist using a list comprehension and the max() function.
  • Pad each sublist with empty strings to make them the same length using another list comprehension.
  • Convert the padded list to a numpy array using the np.array() function.
  • Use the transpose (T) method to switch rows and columns.
  • Use a list comprehension and join to concatenate the strings in each row of the transposed array.
  • Print the result.

Below is the implementation of the above approach:

Python3
import numpy as np # initializing list test_list = [["Gfg", "good"], ["is", "for"], ["Best"]] # find the maximum length of a sublist max_len = max(len(sublist) for sublist in test_list) # pad the sublists with empty strings to make them the same length padded_list = [sublist + [''] * (max_len - len(sublist)) for sublist in test_list] # convert the list to a numpy array arr = np.array(padded_list) # use transpose to switch rows and columns arr_t = arr.T # use join to concatenate the strings in each row res = [''.join(row) for row in arr_t] # print the result print("List after column concatenation: " + str(res)) 

OUTPUT:

List after column concatenation: ['GfgisBest', 'goodfor']

Time complexity: O(n^2), where n is the number of elements in the input list.
Auxiliary space: O(n), for the numpy array and the padded list.


Next Article

Similar Reads