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:
Merge Two Lists into List of Tuples - Python
Next article icon

Python | Merge list of tuple into list by joining the strings

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

Sometimes, we are required to convert list of tuples into a list by joining two element of tuple by a special character. This is usually with the cases with character to string conversion. This type of task is usually required in the development domain to merge the names into one element. Let’s discuss certain ways in which this can be performed. Let’s try to understand it better with code examples. 

Method 1: Using list comprehension and join() 

Python3




# Python code to convert list of tuple into list
# by joining elements of tuple
 
# Input list initialisation
Input = [('Hello', 'There'), ('Namastey', 'India'), ('Incredible', 'India')]
 
# using join and list comprehension
Output = ['_'.join(temp) for temp in Input]
 
# printing output
print(Output)
 
 
Output:
['Hello_There', 'Namastey_India', 'Incredible_India']

Time complexity: O(n), where n is the number of tuples in the input list. This is because the code iterates through each tuple in the list once.
Auxiliary space: O(n), where n is the number of tuples in the input list. This is because the code creates a new list of the same length as the input list to store the output.

Method 2: Using map and join() 

Python3




# Python code to convert list of tuple into list
# by joining elements of tuple
 
# Input list initialisation
Input = [('Hello', 'There'), ('Namastey', 'India'), ('Incredible', 'India')]
 
# using map and join
Output = list(map('_'.join, Input))
 
# printing output
print(Output)
 
 
Output:
['Hello_There', 'Namastey_India', 'Incredible_India']

The time complexity of the given program is O(n), where n is the length of the input list. 

The auxiliary space used by the program is O(n), where n is the length of the input list. 

Method#3: Using Recursive method.

  1. Define a recursive function tuple_to_list_recursive that takes an input list of tuples as its parameter.
  2. Check if the input list is empty. If it is, return an empty list.
  3. If the input list is not empty, take the first tuple from the list using the head variable and the remaining tuples using the tail variable.
  4. Join the elements of the head tuple using the ‘_’ separator and add the result to a list.
  5. Call tuple_to_list_recursive recursively with the tail list as the input parameter.
  6. Concatenate the result of step 4 with the result of step 5.
  7. Return the concatenated list.

Python3




def tuple_to_list_recursive(input_list):
    if not input_list:
        return []
    else:
        head, *tail = input_list
        return ['_'.join(head)] + tuple_to_list_recursive(tail)
Input = [('Hello', 'There'), ('Namastey', 'India'), ('Incredible', 'India')]
Output = tuple_to_list_recursive(Input)
print(Output)
#this code contributed by tvsk.
 
 
Output
['Hello_There', 'Namastey_India', 'Incredible_India']

Time complexity: The time complexity of this recursive method is O(n), where n is the number of tuples in the input list. This is because the function processes each tuple in the list exactly once.
Auxiliary space: The auxiliary space complexity of this method is O(n), where n is the number of tuples in the input list. This is because the function creates a new list of length n to store the result, and the recursive calls to the function use O(n) stack space due to the function call stack.

Method 4: Using a for loop

Step-by-step approach:

  • Initialize the input list of tuples.
  • Create an empty list called Output to store the converted tuples.
  • Use a for loop to iterate through each tuple in the Input list.
  • Within the loop, use the join() method to join the elements of the tuple using ‘_’ as the separator and append the joined string to the Output list.
  • Print the Output list.

Below is the implementation of the above approach:

Python3




# Python code to convert list of tuple into list
# by joining elements of tuple
 
# Input list initialization
Input = [('Hello', 'There'), ('Namastey', 'India'), ('Incredible', 'India')]
 
# Using a for loop to join elements of tuples
Output = []
for temp in Input:
    Output.append('_'.join(temp))
 
# Printing output
print(Output)
 
 
Output
['Hello_There', 'Namastey_India', 'Incredible_India']

Time Complexity: O(n), where n is the number of tuples in the Input list, since we only need to iterate through the list once.
Auxiliary Space: O(n), since we need to store the converted tuples in the Output list.

Method 5: Using reduce() function and lambda function

step-by-step approach of the above program:

  1. Import the reduce function from the functools module.
  2. Initialize the input list Input with the given tuples.
  3. Use the reduce function and a lambda function to join the elements of each tuple and add them to the output list.
  4. The reduce function applies the lambda function on the Input list by taking two arguments at a time from the list and concatenating them using _ separator. The output is a single list with all the joined elements.
  5. Print the output list.

Python3




# Importing reduce function from functools module
from functools import reduce
 
# Input list initialization
Input = [('Hello', 'There'), ('Namastey', 'India'), ('Incredible', 'India')]
 
# Using reduce() function and lambda function to join the elements of each tuple and add them to the output list
Output = reduce(lambda lst, tpl: lst + [f"{tpl[0]}_{tpl[1]}"], Input, [])
 
# Printing output
print(Output)
 
 
Output
['Hello_There', 'Namastey_India', 'Incredible_India']

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

Method 6: Using itertools.chain() and map()

We can also use the itertools.chain() function and map() function to flatten the list of tuples and then join the elements. 

  1. We first use the itertools.chain() function to flatten the list of tuples into a single iterable. 
  2. The chain.from_iterable() method takes an iterable of iterables and returns a single iterable that contains all the elements from all the iterables. In this case, we pass the input list Input to chain.from_iterable() to flatten it.
  3. We then use the map() function to apply the _.join() method to each element in the flattened iterable.
  4. The map() function returns a map object, which we convert to a list using the list() function.
  5. The resulting Output list contains the joined elements of the original list of tuples.

Python3




from itertools import chain
 
Input = [('Hello', 'There'), ('Namastey', 'India'), ('Incredible', 'India')]
Output = list(map('_'.join, chain.from_iterable(Input)))
print(Output)
 
 
Output
['H_e_l_l_o', 'T_h_e_r_e', 'N_a_m_a_s_t_e_y', 'I_n_d_i_a', 'I_n_c_r_e_d_i_b_l_e', 'I_n_d_i_a']

The time complexity of this method is O(n), where n is the total number of elements in the input list of tuples.

The auxiliary space of this method is O(n), where n is the total number of elements in the input list of tuples. 



Next Article
Merge Two Lists into List of Tuples - Python
author
everythingispossible
Improve
Article Tags :
  • Python
  • Python Programs
  • 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
  • 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
  • Merge Two Lists into List of Tuples - Python
    The task of merging two lists into a list of tuples involves combining corresponding elements from both lists into paired tuples. For example, given two lists like a = [1, 2, 3] and b = ['a', 'b', 'c'], the goal is to merge them into a list of tuples, resulting in [(1, 'a'), (2, 'b'), (3, 'c')]. Usi
    3 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
  • Convert List Of Tuples To Json String in Python
    We have a list of tuples and our task is to convert the list of tuples into a JSON string in Python. In this article, we will see how we can convert a list of tuples to a JSON string in Python. Convert List Of Tuples To Json String in PythonBelow, are the methods of Convert List Of Tuples To Json St
    3 min read
  • Python | Ways to merge strings into list
    Given n strings, the task is to merge all strings into a single list. While developing an application, there come many scenarios when we need to operate on the string and convert it as some mutable data structure, say list. There are multiple ways we can convert strings into list based on the requir
    4 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
  • How to Join a list of tuples into one list?
    In Python, we may sometime need to convert a list of tuples into a single list containing all elements. Which can be done by several methods. The simplest way to join a list of tuples into one list is by using nested for loop to iterate over each tuple and then each element within that tuple. Let's
    2 min read
  • Python | Convert String to list of tuples
    Sometimes, while working with data, we can have a problem in which we have a string list of data and we need to convert the same to list of records. This kind of problem can come when we deal with a lot of string data. Let's discuss certain ways in which this task can be performed. Method #1: Using
    8 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
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