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:
Create a tuple from string and list - Python
Next article icon

Python – Custom length tuples from String

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

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, ), (7, ), (4, )]

Explanation :  All elements are of length 1.

Method #1 : Using int() + tuple() + split() + list comprehension

The combination of above functions can be used to solve this problem. In this, we perform conversion of string characters using int() and tuple() and split() is used to split on delimiter.

Python3




# Python3 code to demonstrate working of
# Custom length tuples from String
# Using int() + tuple() + split() + list comprehension
 
# initializing string
test_str = '4 6 7, 1 2, 3, 4 6 8 8'
 
# printing original string
print("The original string is : " + str(test_str))
 
# split() used to split on delimiter and
# type casted to int followed by tuple casting
test_str = test_str.split(', ')
res = [tuple(int(ele) for ele in sub.split()) for sub in test_str]
 
# printing result
print("The constructed custom length tuples : " + str(res))
 
 
Output
The original string is : 4 6 7, 1 2, 3, 4 6 8 8 The constructed custom length tuples : [(4, 6, 7), (1, 2), (3, ), (4, 6, 8, 8)]

Time Complexity: O(n), where n is the elements of list
Auxiliary Space: O(n), where n is the size of list

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

The combination of above functions provide yet another way in which this task can be performed. In this we perform task using similar method as above just difference being using map() to extend logic of integer conversion to elements.

Python3




# Python3 code to demonstrate working of
# Custom length tuples from String
# Using map() + int + tuple() + list comprehension + split()
 
# initializing string
test_str = '4 6 7, 1 2, 3, 4 6 8 8'
 
# printing original string
print("The original string is : " + str(test_str))
 
# split() used to split on delimiter and
# using map() to extend logic of element casting
res = [tuple(map(int, sub.split())) for sub in test_str.split(", ")]
 
# printing result
print("The constructed custom length tuples : " + str(res))
 
 
Output
The original string is : 4 6 7, 1 2, 3, 4 6 8 8 The constructed custom length tuples : [(4, 6, 7), (1, 2), (3, ), (4, 6, 8, 8)]

Time Complexity: O(n*n) where n is the number of elements in the list “test_str”. 
Auxiliary Space: O(n) where n is the number of elements in the list “test_str”. 

Method #3: Using a loop and split() method

 step-by-step approach 

  1. Create a string test_str that contains a sequence of integers and commas.
  2. Print the original string using print(“The original string is : ” + str(test_str)).
  3. Initialize an empty list res to store the converted tuples.
  4. Split test_str using the split() method with the argument “,”. This creates a list of substrings separated by commas.
  5. Loop over each substring using a for loop and the variable name sub.
  6. Within the loop, split the substring sub into a list of integers using the split() method again, but without an argument. This creates a list of integers separated by whitespace.
  7. Convert the list of integers into a tuple using the tuple() constructor function.
  8. Append the resulting tuple to the list res using the append() method.
  9. After the loop finishes, print the resulting list of tuples using print(“The constructed custom length tuples : ” + str(res)).

Python3




# initializing string
test_str = '4 6 7, 1 2, 3, 4 6 8 8'
 
# printing original string
print("The original string is : " + str(test_str))
 
# using loop and split() to convert each substring into tuple of integers
res = []
for sub in test_str.split(","):
    tup = tuple(map(int, sub.split()))
    res.append(tup)
 
# printing result
print("The constructed custom length tuples : " + str(res))
 
 
Output
The original string is : 4 6 7, 1 2, 3, 4 6 8 8 The constructed custom length tuples : [(4, 6, 7), (1, 2), (3,), (4, 6, 8, 8)]

Time complexity: O(nm), where n is the number of substrings and m is the maximum length of each substring
Auxiliary space: O(nm), as we are creating a new list to store the resulting tuples



Next Article
Create a tuple from string and list - Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python - Filter Range Length Tuples
    We are given a list of tuples where each tuple contains multiple elements, and our task is to filter out tuples whose lengths do not fall within a specified range. For example, if we have a = [(1, 2), (3, 4, 5), (6,), (7, 8, 9, 10)] and the range (2, 3), we should keep only tuples with 2 or 3 elemen
    3 min read
  • Create a tuple from string and list - Python
    The task of creating a tuple from a string and a list in Python involves combining elements from both data types into a single tuple. The list elements are added as individual items and the string is treated as a single element within the tuple. For example, given a = ["gfg", "is"] and b = "best", t
    3 min read
  • Python | List of tuples to String
    Many times we can have a problem in which we need to perform interconversion between strings and in those cases, we can have a problem in which we need to convert a tuple list to raw, comma separated string. Let's discuss certain ways in which this task can be performed. Method #1: Using str() + str
    8 min read
  • Python - Filter String Tuples if String lengths equals K
    Given List of tuples, filter tuples, whose element strings have length equal to K. Input : test_list = [("ABC", "Gfg", "CS1"), ("Gfg", "Best"), ("Gfg", "WoOW")], K = 3 Output : [('ABC', 'Gfg', 'CS1')] Explanation : All Strings have length 3 in above tuple. Input : test_list = [("ABCD", "Gfg", "CS1")
    6 min read
  • Convert String to Tuple - Python
    When we want to break down a string into its individual characters and store each character as an element in a tuple, we can use the tuple() function directly on the string. Strings in Python are iterable, which means that when we pass a string to the tuple() function, it iterates over each characte
    2 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 | Convert String to tuple list
    Sometimes, while working with Python strings, we can have a problem in which we receive a tuple, list in the comma-separated string format, and have to convert to the tuple list. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop + split() + replace() This is a br
    5 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 - Split a String by Custom Lengths
    Given a String, perform split of strings on the basis of custom lengths. Input : test_str = 'geeksforgeeks', cus_lens = [4, 3, 2, 3, 1] Output : ['geek', 'sfo', 'rg', 'eek', 's'] Explanation : Strings separated by custom lengths.Input : test_str = 'geeksforgeeks', cus_lens = [10, 3] Output : ['geeks
    2 min read
  • Python | Convert String to N chunks tuple
    Sometimes, while working with Python Strings, we can have a problem in which we need to break a string to N sized chunks to a tuple. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + tuple This is one approach in which this task can be performed.
    2 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