Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Get Nth column elements in Tuple Strings
Next article icon

Python | Nth Column vertical string in Matrix

Last Updated : 09 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while working with Python Matrix, we can have a problem in which we need to access the Matrix in vertical form and extract strings from the same, that too as a string, not merely as a list of characters. This task has its application in gaming in which we need to extract strings during crosswords. Let’s discuss a way in which this task can be performed. 

Method 1: Using list comprehension + join() 

We achieve the task in this method in 2 steps. In 1st step, the Nth column elements are extracted using list comprehension. In 2nd step, these elements are joined together to perform the characters-to-string conversion. 

Python3




# Python3 code to demonstrate working of
# Nth Column vertical string in Matrix
# Using join() + list comprehension
 
# initializing list
test_list = [('a', 'g', 'v'), ('e', 'f', 8), ('b', 'g', 0)]
 
# printing list
print("The original list : " + str(test_list))
 
# initializing Nth column
N = 1
 
# Nth Column vertical string in Matrix
# Using join() + list comprehension
temp = [sub[N] for sub in test_list]
res = "".join(temp)
 
# Printing result
print("Constructed vertical string : " + str(res))
 
 
Output
The original list : [('a', 'g', 'v'), ('e', 'f', 8), ('b', 'g', 0)] Constructed vertical string : gfg

Time complexity: O(n), where n is the length of the input list test_list. 
Auxiliary space: O(1) because the amount of extra space used is constant and does not depend on the size of the input. Specifically, the only extra space used is for the temp list and the res string, both of which require O(n) space, where n is the length of test_list. 

Method 2: Using numpy() 

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

Another approach could be using numpy, which can extract the Nth column of a matrix as a numpy array and then use numpy.array2string() to convert the array to a string. This approach would have a time complexity of O(n) where n is the number of rows in the matrix, and a space complexity of O(n) as well, as it requires a new numpy array to be created.

Python3




import numpy as np
test_matrix = np.array([['a', 'g', 'v'], ['e', 'f', 8], ['b', 'g', 0]])
 
# initializing Nth column
N = 1
# Extracting Nth column
temp = test_matrix[:, N]
# Converting numpy array to string
# Printing result
print("Constructed vertical string : " + "".join(temp))
 
 

Output:

Constructed vertical string : gfg

Time complexity: O(n) 
Auxiliary space: O(n)

Method 3: Using for loop:

This method iterates through each tuple in the list and appends the Nth element to a string. Finally, the resulting string is printed as the vertical string.

Python3




# initializing list
test_list = [('a', 'g', 'v'), ('e', 'f', 8), ('b', 'g', 0)]
 
# printing list
print("The original list : " + str(test_list))
 
# initializing Nth column
N = 1
 
# Nth Column vertical string in Matrix
# Using for loop
res = ""
for sub in test_list:
    res += str(sub[N])
 
# Printing result
print("Constructed vertical string : " + str(res))
 
 
Output
The original list : [('a', 'g', 'v'), ('e', 'f', 8), ('b', 'g', 0)] Constructed vertical string : gfg

Time complexity: O(N), where N is the number of tuples in the list. 
Auxiliary Space: O(N), where N is the number of tuples in the list.

Method 4: Iterating through the rows of the matrix and appending the Nth character to a string variable.

In this approach, initialize an empty string variable res and iterate through the rows of the matrix using a for loop. For each row, append the Nth character (i.e., the character at index N) to the res variable. Finally, print the constructed vertical string.

Approach:

  • Initialize a list of tuples test_list that represents the matrix.
  • Print the original list to verify it is correct.
  • Initialize the value of N to the index of the column we want to extract.
  • Initialize an empty string variable res to store the extracted vertical string.
  • Iterate through each row in the test_list matrix using a for loop.
    • For each row, append the Nth character (i.e., the character at index N) to the res variable.
    • After iterating through all rows, print the constructed vertical string
  • Print the res.

Python3




# Python3 code to demonstrate working of
# Nth Column vertical string in Matrix
# Using for loop
 
# initializing list
test_list = [('a', 'g', 'v'), ('e', 'f', 8), ('b', 'g', 0)]
 
# printing list
print("The original list : " + str(test_list))
 
# initializing Nth column
N = 1
 
# Using for loop
res = ''
for row in test_list:
    res += row[N]
 
# Printing result
print("Constructed vertical string : " + str(res))
 
 
Output
The original list : [('a', 'g', 'v'), ('e', 'f', 8), ('b', 'g', 0)] Constructed vertical string : gfg

The time complexity of this approach is O(n), where n is the number of rows in the matrix. 
The auxiliary space complexity is O(1), as we are only using a single string variable to store the result.

Method 5: Using map() and str.join()

Approach:

  1. Initialize the list of tuples with the required values.
  2. Initialize the Nth column value that needs to be extracted.
  3. Use the map() function to extract the Nth column from each tuple.
  4. Convert the map object to a list.
  5. Join the extracted characters using the join() method.
  6. Return the constructed vertical string.
  7. Print the result.

Python3




# Python3 code to demonstrate working of
# Nth Column vertical string in Matrix
# Using map() and join()
 
# initializing list
test_list = [('a', 'g', 'v'), ('e', 'f', 8), ('b', 'g', 0)]
 
# printing list
print("The original list : " + str(test_list))
 
# initializing Nth column
N = 1
 
# Using map() and join()
res = ''.join(list(map(lambda x: x[N], test_list)))
 
# Printing result
print("Constructed vertical string : " + str(res))
 
 
Output
The original list : [('a', 'g', 'v'), ('e', 'f', 8), ('b', 'g', 0)] Constructed vertical string : gfg

Time complexity: O(n), where n is the number of tuples in the list.
Auxiliary space: O(n), where n is the number of tuples in the list.

Method 6: Using pandas library

Here’s another approach that uses the pandas library to extract the Nth column of the input matrix and string concatenation to construct the final vertical string.

Step-by-step approach:

  1. Import the pandas library.
  2. Initialize the input list test_list as a pandas DataFrame.
  3. Initialize the variable N to specify the column index to extract.
  4. Use the iloc attribute of the DataFrame to extract the Nth column as a Series object.
  5. Use the str.cat() method of the Series object to concatenate the elements into a single string.
  6. Print the final vertical string.

Python3




import pandas as pd
 
# initializing list
test_list = [('a', 'g', 'v'), ('e', 'f', 8), ('b', 'g', 0)]
 
# convert list to DataFrame
df = pd.DataFrame(test_list)
 
# initializing Nth column
N = 1
 
# extract Nth column as a Series object
col = df.iloc[:, N]
 
# concatenate elements into a single string
res = col.str.cat()
 
# print final vertical string
print("Constructed vertical string : " + str(res))
 
 
OUTPUT: Constructed vertical string : gfg

Time complexity: O(n), where n is the number of elements in the input list.

Auxiliary space: O(n), to store the elements of the input list as a DataFrame. However, this approach may be more memory-efficient than some of the other methods, especially for very large input lists.



Next Article
Python - Get Nth column elements in Tuple Strings
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python | Search in Nth Column of Matrix
    Sometimes, while working with Python Matrix, we can have a problem in which we need to check if an element is present or not. This problem is simpler, but a variation to it can be to perform a check in a particular column of Matrix. Let's discuss a shorthand by which this task can be performed. Meth
    10 min read
  • Python - Rear column in Multi-sized Matrix
    Given a Matrix with variable lengths rows, extract last column. Input : test_list = [[3, 4, 5], [7], [8, 4, 6], [10, 3]] Output : [5, 7, 6, 3] Explanation : Last elements of rows filtered. Input : test_list = [[3, 4, 5], [7], [8, 4, 6]] Output : [5, 7, 6] Explanation : Last elements of rows filtered
    4 min read
  • Python - Get Nth column elements in Tuple Strings
    Yet another peculiar problem that might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This article solves the problem of extracting only the
    8 min read
  • Python - Vertical Concatenation in Matrix
    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"], ["i
    3 min read
  • Python - Convert Integer Matrix to String Matrix
    Given a matrix with integer values, convert each element to String. Input : test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6]] Output : [['4', '5', '7'], ['10', '8', '3'], ['19', '4', '6']] Explanation : All elements of Matrix converted to Strings. Input : test_list = [[4, 5, 7], [10, 8, 3]] Output : [
    6 min read
  • Python | String List to Column Character Matrix
    Sometimes, while working with Python lists, we can have a problem in which we need to convert the string list to Character Matrix where each row is String list column. This can have possible application in data domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using
    5 min read
  • Python - Interconvert Horizontal and Vertical String
    Given a String, convert to vertical if horizontal and vice-versa. Input : test_str = 'geeksforgeeks' Output : g e e k s Explanation : Horizontal String converted to Vertical. Input : test_str = g e e k s Output : 'geeks' Explanation : Vertical String converted to Horizontal. Method #1 : [Horizontal
    2 min read
  • Summation Matrix columns - Python
    The task of summing the columns of a matrix in Python involves calculating the sum of each column in a 2D list or array. For example, given the matrix a = [[3, 7, 6], [1, 3, 5], [9, 3, 2]], the goal is to compute the sum of each column, resulting in [13, 13, 13]. Using numpy.sum()numpy.sum() is a hi
    2 min read
  • Python - Summation of kth column in a matrix
    Sometimes, while working with Python Matrix, we may have a problem in which we require to find the summation of a particular column. This can have a possible application in day-day programming and competitive programming. Let’s discuss certain ways in which this task can be performed. Method #1 : Us
    8 min read
  • Python - String Matrix Concatenation
    Sometimes, while working with Matrix we can have a problem in which we have Strings and we need a universal concatenation of all the String present in it. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + join() We can solve this problem using lis
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences