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:
Concatenate all Elements of a List into a String - Python
Next article icon

Python – String concatenation in Heterogeneous list

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

Sometimes, while working with Python, we can come across a problem in which we require to find the concatenation of strings. This problem is easier to solve. But this can get complex cases we have a mixture of data types to go along with it. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using loop + conditions 
We can employ a brute force method to type caste check each element, if it’s a string we concatenate it. This can ensure that only strings are concatenated and hence can solve the problem.

Python3




# Python3 code to demonstrate working of
# String concatenation in Heterogeneous list
# using loop + conditions
 
# initializing list
test_list = [5, 6, "gfg ", 8, (5, 7), ' is', 9, ' best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# String concatenation in Heterogeneous list
# using loop + conditions
res = ''
for ele in test_list:
    if type(ele) == str:
        res += ele
 
# printing result
print("Concatenation of strings in list : " + str(res))
 
 
Output
The original list is : [5, 6, 'gfg ', 8, (5, 7), ' is', 9, ' best'] Concatenation of strings in list : gfg  is best

Time Complexity: O(n*n) where n is the number of elements in the string list. The loop + conditions is used to perform the task and it takes O(n*n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the string list.

Method #2 : Using join() + isinstance() 
This problem can also be solved using the inbuilt function of join() and it also supports the instance filter using isinstance() which can be fed with strings and hence solve the problem.

Python3




# Python3 code to demonstrate working of
# String concatenation in Heterogeneous list
# using join() + isinstance()
 
# initializing list
test_list = [5, 6, "gfg ", 8, (5, 7), ' is', 9, ' best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# String concatenation in Heterogeneous list
# using join() + isinstance()
res = "".join(filter(lambda i: isinstance(i, str), test_list))
 
# printing result
print("Concatenation of strings in list : " + str(res))
 
 
Output
The original list is : [5, 6, 'gfg ', 8, (5, 7), ' is', 9, ' best'] Concatenation of strings in list : gfg  is best

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

Method#3: Using reduce + type 
This problem can be solved using reduce and type function. We use reduce for iteration over the list and type is used to check the type of element in iteration if it is string type then add it in our result else leave it. 

Python3




# Python3 code to demonstrate working of
# String concatenation in Heterogeneous list
# using reduce + type
 
from functools import reduce
# initializing list
test_list = [5, 6, "gfg ", 8, (5, 7), ' is', 9, ' best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# String concatenation in Heterogeneous list
# using reduce + type()
ans = reduce(lambda x, y: x + y if type(y) == str else x, test_list, "")
 
# printing result
print("Concatenation of strings in list : " + ans)
 
 
Output
The original list is : [5, 6, 'gfg ', 8, (5, 7), ' is', 9, ' best'] Concatenation of strings in list : gfg  is best

Method #4: Using list comprehension

Step-by-step approach:

  • Initialize the list test_list with heterogeneous data types.
  • Print the original list.
  • Use list comprehension to iterate over each element of test_list and return the element only if it is an instance of str.
  • Concatenate the filtered elements using join() method and store it in the variable res.
  • Print the concatenated string.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# String concatenation in Heterogeneous list
# using list comprehension
 
# initializing list
test_list = [5, 6, "gfg ", 8, (5, 7), ' is', 9, ' best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# String concatenation in Heterogeneous list
# using list comprehension
res = ''.join([ele for ele in test_list if isinstance(ele, str)])
 
# printing result
print("Concatenation of strings in list : " + str(res))
 
 
Output
The original list is : [5, 6, 'gfg ', 8, (5, 7), ' is', 9, ' best'] Concatenation of strings in list : gfg  is best

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



Next Article
Concatenate all Elements of a List into a String - Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python | Convert heterogeneous type String to List
    Sometimes, while working with data, we can have a problem in which we need to convert data in string into a list, and the string contains elements from different data types like boolean. This problem can occur in domains in which a lot of data types are used. Let's discuss certain ways in which this
    6 min read
  • Python | Concatenate N consecutive elements in String list
    Sometimes, while working with data, we can have a problem in which we need to perform the concatenation of N consecutive Strings in a list of Strings. This can have many applications across domains. Let's discuss certain ways in which this task can be performed. Method #1: Using format() + zip() + i
    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
  • Concatenate all Elements of a List into a String - Python
    We are given a list of words and our task is to concatenate all the elements into a single string with spaces in between. For example, given the list: li = ['hello', 'geek', 'have', 'a', 'geeky', 'day'] after concatenation, the result will be: "hello geek have a geeky day". Using str.join()str.join(
    3 min read
  • Python - All possible concatenations in String List
    Sometimes, while working with String lists, we can have a problem in which we need to perform all possible concatenations of all the strings that occur in list. This kind of problem can occur in domains such as day-day programming and school programming. Let's discuss a way in which this task can be
    3 min read
  • Python - Concatenate String values in Dictionary List
    Sometimes, while working with Python records data, we can have a problem in which we require to perform concatenation of string values of keys by matching at particular key like ID. This kind of problem can have application in web development domain. Let's discuss certain way in which this task can
    4 min read
  • Python - Horizontal Concatenation of Multiline Strings
    Horizontal concatenation of multiline strings involves merging corresponding lines from multiple strings side by side using methods like splitlines() and zip(). Tools like itertools.zip_longest() help handle unequal lengths by filling missing values, and list comprehensions format the result. Using
    3 min read
  • Python - Concatenate Ranged Values in String list
    Given list of strings, perform concatenation of ranged values from the Strings list. Input : test_list = ["abGFGcs", "cdforef", "asalloi"], i, j = 3, 5 Output : FGorll Explanation : All string sliced, FG, or and ll from all three strings and concatenated. Input : test_list = ["aGFGcs", "cforef", "aa
    5 min read
  • Python - Concatenate Kth element in Tuple List
    While working with tuples, we store different data as different tuple elements. Sometimes, there is a need to print a specific information from the tuple. For instance, a piece of code would want just names to be printed of all the student data in concatenated format. Lets discuss certain ways how o
    8 min read
  • Most efficient way to Concatenate Strings in Python
    Concatenation is an operation that is very frequently used in various problems related to strings. There are multiple methods to concat strings in various languages. Python is also such a language that supports various string concatenation methods. But have you ever wondered which one is the most ef
    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