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 - Count elements in tuple list
Next article icon

Python – Get Nth column elements in Tuple Strings

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

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 Nth index element of each string in tuple. Let’s discuss certain ways in which this problem can be solved. 

Method #1: Using list comprehension Almost every problem can be solved using list comprehension as a shorthand for a naive approach and this problem isn’t an exception. In this, we just iterate through each list picking just the Nth index element to build the resultant list. 

Python3




# Python3 code to demonstrate
# Nth column in Tuple Strings
# using list comprehension
 
# initializing tuple
test_tuple = ('GfG', 'for', 'Geeks')
 
# initializing N
N = 1
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
# using list comprehension
# Nth column in Tuple Strings
res = list(sub[N] for sub in test_tuple)
 
# print result
print("The Nth index string character list : " + str(res))
 
 
Output : 
The original tuple : ('GfG', 'for', 'Geeks') The Nth index string character list : ['f', 'o', 'e']

Time complexity: O(n), where n is the length of the tuple. This is because the list comprehension iterates through each element of the tuple and extracts the Nth index string character from each element.
Auxiliary space: O(n), where n is the length of the tuple. This is because the program creates a list with n elements, where each element is a string character extracted from the corresponding tuple element.

Method #2: Using next() + zip() This particular task can also be performed using the combination of above two in more efficient way, using the iterators to do this task. The zip function can be used bind together the string elements. 

steps to implement this approach:

  1. Initialize the tuple.
  2. Print the original tuple.
  3. Initialize the index of the column to be extracted.
  4. Use the zip() function with the asterisk operator to convert the tuple into a list of individual characters.
  5. Use a for loop to iterate through the list up to the index of the desired column.
  6. Use the next() function to move the iterator to the desired column.
  7. Convert the column iterator to a list to extract the characters in the desired column.
  8. Print the list of characters in the desired column.

Python3




# Python3 code to demonstrate
# Nth column in Tuple Strings
# using next() + zip()
 
# initializing tuple
test_tuple = ('GfG', 'for', 'Geeks')
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
# initializing N
N = 1
 
# using next() + zip()
# Nth column in Tuple Strings
temp = zip(*test_tuple)
for idx in range(0, N):
    next(temp)
res = list(next(temp))
 
# print result
print("The Nth index string character list : " + str(res))
 
 
Output : 
The original tuple : ('GfG', 'for', 'Geeks') The Nth index string character list : ['f', 'o', 'e']

Time Complexity: O(n*n), where n is the length of the input list. This is because we’re using next() + zip() which has a time complexity of O(n*n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.

Method 3:  Using map() and lambda

We can use the map() function along with a lambda function to extract the Nth index character from each string in the tuple. The map() function applies the lambda function to each element of the tuple and returns a map object. We then convert this map object to a list using the list() function and store the result in the variable res. Finally, we print the result.

Python3




# initializing tuple
test_tuple = ('GfG', 'for', 'Geeks')
 
# initializing N
N = 1
 
# printing original tuple
print("The original tuple : ", test_tuple)
 
# using map() and lambda
# Nth column in Tuple Strings
res = list(map(lambda sub: sub[N], test_tuple))
 
# print result
print("The Nth index string character list : ", res)
 
 
Output
The original tuple :  ('GfG', 'for', 'Geeks') The Nth index string character list :  ['f', 'o', 'e']

Time complexity: O(N), where N is the number of elements in the given tuple. This is because the program loops through each element of the tuple once to extract the Nth index character.
Auxiliary space: O(N), as the program creates a new list res of size N to store the Nth index character from each string in the tuple. 

Method 4: Use a for loop to iterate through the tuples, and then use string slicing to extract the Nth character from each string in the tuple.

Step-by-step approach:

  • Initialize a tuple named test_tuple with three string values: ‘GfG’, ‘for’, and ‘Geeks’.
  • Print the original tuple using the print() function and string concatenation.
  • Initialize the value of N to 1. This will be used to extract the second column of each string in the tuple.
  • Create an empty list named res, which will be used to store the characters from the Nth column of each string.
  • Using a for loop, iterate through each string in the test_tuple.
    • Inside the for loop, use string slicing to extract the character at index N (which is the second column in this case). Append this character to the res list.
  • Print the list res which contains the characters from the Nth column of each string in the tuple.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate
# Nth column in Tuple Strings
# using a for loop and string slicing
 
# initializing tuple
test_tuple = ('GfG', 'for', 'Geeks')
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
# initializing N
N = 1
 
# using a for loop and string slicing
# Nth column in Tuple Strings
res = []
for string in test_tuple:
    res.append(string[N])
 
# print result
print("The Nth index string character list : " + str(res))
 
 
Output
The original tuple : ('GfG', 'for', 'Geeks') The Nth index string character list : ['f', 'o', 'e']

Time complexity: O(n), where n is the number of strings in the tuple
Auxiliary space: O(n), where n is the number of strings in the tuple, since we are storing the Nth character of each string in a list.

Method 5:  Using the str.join() method and list comprehension.

Step-by-step approach:

  1. Initialize the tuple with the given strings.
  2. Print the original tuple.
  3. Initialize the value of N to the index of the character to be extracted.
  4. Use list comprehension to iterate through the strings in the tuple and extract the Nth character from each string.
  5. Store the extracted characters in a list.
  6. Print the resulting list.

Python3




# Python3 code to demonstrate
# Nth column in Tuple Strings
# using join() and list comprehension
 
# initializing tuple
test_tuple = ('GfG', 'for', 'Geeks')
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
# initializing N
N = 1
 
# using join() and list comprehension
# Nth column in Tuple Strings
res = [string[N] for string in test_tuple]
 
# print result
print("The Nth index string character list : " + str(res))
 
 
Output
The original tuple : ('GfG', 'for', 'Geeks') The Nth index string character list : ['f', 'o', 'e']

Time complexity: O(n), where n is the length of the tuple.
Auxiliary space: O(n), where n is the length of the tuple (to store the list of extracted characters).

Method 6: Using list() and enumerate() function

Step-by-step approach:

  • Initialize the tuple, test_tuple.
  • Initialize the value of N, which is the index of the character to be extracted from each string.
  • Use the list() and enumerate() functions to create a list of tuples, where each tuple contains the index of the string and the string itself.
  • Use a list comprehension to extract the Nth character from each string in the list of tuples.
  • Return the list of extracted characters.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate
# Nth column in Tuple Strings
# using list() and enumerate()
 
# initializing tuple
test_tuple = ('GfG', 'for', 'Geeks')
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
# initializing N
N = 1
 
# using list() and enumerate()
# Nth column in Tuple Strings
res = [t[N] for i, t in enumerate(list(test_tuple))]
 
# print result
print("The Nth index string character list : " + str(res))
 
 
Output
The original tuple : ('GfG', 'for', 'Geeks') The Nth index string character list : ['f', 'o', 'e']

Time complexity: O(n), where n is the length of the tuple.
Auxiliary space: O(n), where n is the length of the tuple.



Next Article
Python - Count elements in tuple list
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python - Count elements in tuple list
    Sometimes, while working with data in form of records, we can have a problem in which we need to find the count of all the records received. This is a very common application that can occur in Data Science domain. Let’s discuss certain ways in which this task can be performed. Method #1: Using len()
    5 min read
  • Python - Count elements in record tuple
    Sometimes, while working with data in form of records, we can have a problem in which we need to find the total element counts of all the records received. This is a very common application that can occur in Data Science domain. Let’s discuss certain ways in which this task can be performed. Method
    5 min read
  • Python | Counting Nth tuple element
    Sometimes, while working with Python, we can have a problem in which we need to count the occurrence of a particular's elements. This kind of problem is quite common while working with records. Let's discuss a way in which this task can be performed. Method #1 : Using Counter() + generator expressio
    5 min read
  • Python | Extend tuples by count of elements in tuple
    Sometimes, while working with data, we can have an application in which we need to duplicate tuple elements by the amount of element count. This is very unique application but can occur in certain cases. Let's discuss certain ways in which this task can be performed. Method #1: Using nested loops Th
    6 min read
  • Python | Nth Column vertical string in Matrix
    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 cr
    7 min read
  • Python | Tuple Column element frequency
    In Python, we need to handle various forms of data and one among them is a list of tuples in which we may have to perform any kind of operation. This particular article discusses the ways of finding the frequency of the Kth element in the list of tuples. Let’s discuss certain ways in which this can
    5 min read
  • Python | Rear elements from 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
    5 min read
  • Python - Custom length tuples from String
    Given a String, extract tuple list, with each tuple being of custom length, delimited using comma. Input : test_str = "6 6 7, 3 4, 2" Output : [(6, 6, 7), (3, 4), (2, )] Explanation : The customs lengths being 3, 2, 1 have been converted to tuple list. Input : test_str = "7, 7, 4" Output : [(7, ), (
    4 min read
  • Convert tuple to string in Python
    The goal is to convert the elements of a tuple into a single string, with each element joined by a specific separator, such as a space or no separator at all. For example, in the tuple ('Learn', 'Python', 'Programming'), we aim to convert it into the string "Learn Python Programming". Let's explore
    3 min read
  • Python - Element Index in Range Tuples
    Sometimes, while working with Python data, we can have a problem in which we need to find the element position in continuous equi ranged tuples in list. This problem has applications in many domains including day-day programming and competitive programming. Let's discuss certain ways in which this t
    6 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