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 - Convert List of Integers to a List of Strings
Next article icon

Python program to convert a list of strings with a delimiter to a list of tuple

Last Updated : 08 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a List containing strings with a particular delimiter. The task is to remove the delimiter and convert the string to the list of tuple.

Examples:

Input : test_list = [“1-2”, “3-4-8-9”], K = “-” 
Output : [(1, 2), (3, 4, 8, 9)] 
Explanation : After splitting, 1-2 => (1, 2).
 

Input : test_list = [“1*2”, “3*4*8*9”], K = “*” 
Output : [(1, 2), (3, 4, 8, 9)] 
Explanation : After splitting, 1*2 => (1, 2). 

Method #1 : Using list comprehension + split()

In this, first, each string is split using split() with K as an argument, then this is extended to all the Strings using list comprehension.

Python3




# Python3 code to demonstrate working of
# Convert K delim Strings to Integer Tuple List
# Using list comprehension + split()
 
# initializing list
test_list = ["1-2", "3-4-8-9", "4-10-4"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = "-"
 
# conversion using split and list comprehension
# int() is used for conversion
res = [tuple(int(ele) for ele in sub.split(K)) for sub in test_list]
 
# printing result
print("The converted tuple list : " + str(res))
 
 
Output
The original list is : ['1-2', '3-4-8-9', '4-10-4'] The converted tuple list : [(1, 2), (3, 4, 8, 9), (4, 10, 4)]

Time Complexity: O(n) where n is the number of elements in the list “test_list”. 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”. 

Method #2 : Using map() + split() + list comprehension

In this, the task of extension of integral extension logic is done using map() and then list comprehension is used to perform the task of construction of the list.

Python3




# Python3 code to demonstrate working of
# Convert K delim Strings to Integer Tuple List
# Using map() + split() + list comprehension
 
# initializing list
test_list = ["1-2", "3-4-8-9", "4-10-4"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = "-"
 
# extension logic using map()
# int() is used for conversion
res = [tuple(map(int, sub.split(K))) for sub in test_list]
 
# printing result
print("The converted tuple list : " + str(res))
 
 
Output
The original list is : ['1-2', '3-4-8-9', '4-10-4'] The converted tuple list : [(1, 2), (3, 4, 8, 9), (4, 10, 4)]

The time complexity is O(n*m), where n is the number of elements in the list and m is the maximum length of a single element in the list. 

The Auxiliary space is O(nm) 

Method #3: Using for loop and append() method

Iterate through each string of the list using a for loop, split each string by the K delimiter, convert the split strings to integers using the map() function, and append the tuple of integers to a result list.

Step-by-step approach:

  • Initialize an empty list called ‘result‘ to store the converted tuples.
  • Use a for loop to iterate through each string in the input list, ‘test_list‘.
  • Inside the for loop, split each string by the K delimiter using the split() method and store the split strings in a list called ‘split_list‘.
  • Use the map() function with int() to convert each string in the ‘split_list‘ to an integer, and store the result in a new list called ‘int_list‘.
  • Create a tuple from the ‘int_list‘ using the tuple() function, and append it to the ‘result’ list.
  • After the for loop is completed, print the ‘result‘ list.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Convert K delim Strings to Integer Tuple List
# Using for loop and append() method
 
# initializing list
test_list = ["1-2", "3-4-8-9", "4-10-4"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = "-"
 
# initializing empty list for result
result = []
 
# for loop and append method
for sub in test_list:
    # split each string by K delimiter
    split_list = sub.split(K)
     
    # map() to convert split strings to integers
    int_list = list(map(int, split_list))
     
    # create tuple from int_list and append to result
    result.append(tuple(int_list))
 
# printing result
print("The converted tuple list : " + str(result))
 
 
Output
The original list is : ['1-2', '3-4-8-9', '4-10-4'] The converted tuple list : [(1, 2), (3, 4, 8, 9), (4, 10, 4)]

Time complexity: O(nm), where ‘n’ is the number of strings in the input list and ‘m’ is the average number of integers in each string.
Auxiliary space: O(nm), for the ‘result’ list that stores the converted tuples.

Method #4: Using regex and for loop

We can also use regular expressions to split the strings at the delimiter and convert the resulting strings to integers using a for loop and the append() method.

  1. Import the ‘re’ module for working with regular expressions.
  2. Initialize a list named ‘test_list’ with some sample data that contains strings separated by a delimiter ‘-‘.
  3. Print the original list to show the input data.
  4. Initialize a variable named ‘K’ with the delimiter used to separate the strings.
  5. Create a regular expression pattern using the ‘re.compile()’ method that matches any sequence of one or more digits.
  6. Initialize an empty list named ‘res’ to store the resulting tuples.
  7. Iterate through each string in the ‘test_list’ using a ‘for’ loop.
  8. Use the ‘pattern.findall()’ method to find all the substrings in the current string that match the pattern.
  9. Convert each substring to an integer using a ‘for’ loop and the ‘int()’ method.
  10. Combine the resulting integers into a tuple using the ‘tuple()’ method.
  11. Append the tuple to the ‘res’ list.
  12. Print the final ‘res’ list to show the converted tuple list.

Python3




import re
 
# initializing list
test_list = ["1-2", "3-4-8-9", "4-10-4"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K and regex pattern
K = "-"
pattern = re.compile(r'\d+')
 
# initializing result list
res = []
 
# for loop and append() method
for sub in test_list:
    sub_list = pattern.findall(sub)
    sub_tuple = tuple(int(num) for num in sub_list)
    res.append(sub_tuple)
 
# printing result
print("The converted tuple list : " + str(res))
 
 
Output
The original list is : ['1-2', '3-4-8-9', '4-10-4'] The converted tuple list : [(1, 2), (3, 4, 8, 9), (4, 10, 4)]

Time Complexity: The time complexity of this method is O(n*m), where n is the length of the input list and m is the average length of each string in the input list.
Auxiliary Space: The auxiliary space used by this method is O(n*m), as we are creating a new list to store the resulting tuples.

Method #6: Using a lambda function with map() and split()

In this approach, we can use a lambda function with map() and split() to split each element of the given list by the separator “-” and convert the resulting sublists of strings into tuples of integers.

Step-by-step approach:

  • Initialize the given list.
  • Define a lambda function that takes a string as input, splits it by “-“, and maps the resulting sublists of strings to tuples of integers using the map() function.
  • Apply the lambda function to each element of the given list using the map() function.
  • Convert the resulting map object to a list using the list() function and store it in a variable.
  • Print the resulting list.

Below is the implementation of the above approach:

Python3




# initializing list
test_list = ["1-2", "3-4-8-9", "4-10-4"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# define lambda function
split_and_convert = lambda s: tuple(map(int, s.split("-")))
 
# apply lambda function to each element of the list
result = list(map(split_and_convert, test_list))
 
# printing result
print("The converted tuple list : " + str(result))
 
 
Output
The original list is : ['1-2', '3-4-8-9', '4-10-4'] The converted tuple list : [(1, 2), (3, 4, 8, 9), (4, 10, 4)]

Time complexity: O(nm), where n is the length of the given list and m is the maximum number of elements in any sublist after splitting.
Auxiliary space: O(nm), where n is the length of the given list and m is the maximum number of elements in any sublist after splitting.



Next Article
Python - Convert List of Integers to a List of Strings
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python List-of-Tuples
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Convert list of strings to list of tuples in Python
    Sometimes we deal with different types of data types and we require to inter-convert from one data type to another hence interconversion is always a useful tool to have knowledge. This article deals with the converse case. Let's discuss certain ways in which this can be done in Python. Method 1: Con
    5 min read
  • Python program to Convert a elements in a list of Tuples to Float
    Given a Tuple list, convert all possible convertible elements to float. Input : test_list = [("3", "Gfg"), ("1", "26.45")] Output : [(3.0, 'Gfg'), (1.0, 26.45)] Explanation : Numerical strings converted to floats. Input : test_list = [("3", "Gfg")] Output : [(3.0, 'Gfg')] Explanation : Numerical str
    5 min read
  • Convert List of Tuples to List of Strings - Python
    The task is to convert a list of tuples where each tuple contains individual characters, into a list of strings by concatenating the characters in each tuple. This involves taking each tuple, joining its elements into a single string, and creating a new list containing these strings. For example, gi
    3 min read
  • Python - Convert List of Integers to a List of Strings
    We are given a list of integers and our task is to convert each integer into its string representation. For example, if we have a list like [1, 2, 3] then the output should be ['1', '2', '3']. In Python, there are multiple ways to do this efficiently, some of them are: using functions like map(), re
    3 min read
  • Python program to convert tuple into list by adding the given string after every element
    Given a Tuple. The task is to convert it to List by adding the given string after every element. Examples: Input : test_tup = (5, 6, 7), K = "Gfg" Output : [5, 'Gfg', 6, 'Gfg', 7, 'Gfg'] Explanation : Added "Gfg" as succeeding element. Input : test_tup = (5, 6), K = "Gfg" Output : [5, 'Gfg', 6, 'Gfg
    5 min read
  • Convert Set of Tuples to a List of Lists in Python
    Sets and lists are two basic data structures in programming that have distinct uses. It is sometimes necessary to transform a collection of tuples into a list of lists. Each tuple is converted into a list throughout this procedure, and these lists are subsequently compiled into a single, bigger list
    3 min read
  • Python | Convert List of lists to list of Strings
    Interconversion of data is very popular nowadays and has many applications. In this scenario, we can have a problem in which we need to convert a list of lists, i.e matrix into list of strings. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + joi
    4 min read
  • How To Convert Comma-Delimited String to a List In Python?
    In Python, converting a comma-separated string to a list can be done by using various methods. In this article, we will check various methods to convert a comma-delimited string to a list in Python. Using str.split()The most straightforward and efficient way to convert a comma-delimited string to a
    1 min read
  • Python | Convert mixed data types tuple list to string list
    Sometimes, while working with records, we can have a problem in which we need to perform type conversion of all records into a specific format to string. This kind of problem can occur in many domains. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehensi
    5 min read
  • Python Program to Convert a List to String
    In Python, converting a list to a string is a common operation. In this article, we will explore the several methods to convert a list into a string. The most common method to convert a list of strings into a single string is by using join() method. Let's take an example about how to do it. Using th
    3 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