Join List of items of different types as String in Python

In Python, a list can have items of different type. In this article, ee will learn about the methods through which we can join a list of items of different types, as a string in Python Programming language.

Table Of Contents

Introduction

A List is of two types in Python,

  • Homogenous Lists : All items in the list are of similar data type
  • Heterogeneous Lists : Items in the list are of different data types.

Here we are dealing with Heterogeneous Lists.

Example :

Advertisements
# initialized a list of items with different data types.
example_list = ['Python','AI','ML','thispointer.com',2,7.8,91,'34']

# type() will print the data type of var example_list which happens to be be of class list.
print(type(example_list))

Output :

<class 'list'>

In the above example, we have items of different data types in example_list, which is of list type. We need to join the items of example_list in a string. Joined string should be like,

Python AI ML thispointer.com 2 7.8 91 34

We will learn about some methods through which we can accomplish our job.

Method 1 : Using map()

First technique, that we will be using to convert all the elements of a Heterogeneous List into a string is a combination of map(), str() and join() functions. Let’s understand about these functions first.

  • map() : A map() operation appplies a function to each element in the sequence like list, tuple, etc, and returns a new sequence containing the results.
  • str() : str() converts the object of any other data type to string. It takes three parameters :
    • object : any object which needs to be converterd into string.
    • encoding : encoding of the object, default = UTF-8.
    • errors : error handling if the decoding fails.
  • join() : This method of string class accepts an iterable as argument and joins all the strings in iterable to a big string. This method raises a TypeError if the elemets of the given iterable is not of string type.

See the example code below,

# initialized a list of items with different data types.
example_list = ['Python', 'AI', 'ML', 'thispointer.com', 2, 7.8, 91, '34']

# type() will print the data type of var example_list
# which happens to be be of class list.
print(type(example_list))

# converting a list to string using join 
new_str = ' '.join(map(str, example_list))

print(new_str)

# type() will print the data type of var new_str
# which happens to be of class str.
print(type(new_str))

OUTPUT :

<class 'list'>
Python AI ML thispointer.com 2 7.8 91 34
<class 'str'>

In the above example, by using the map() and str() methods, we have successfully converted the data type of all items of list to string. Then we joined all the strings in list to a create a big single string.

Method 2 : Using join() method

Here what we will use the join() function of class str to join the items of of a list. We can use a for loop to iterate over the items of the list and then use str() function to convert them in into string type. Then use join() method to join them with a seprarator. For example if we use ‘,’ as a separator with join() method then it will create the new string with commas separating each item. Similarly, we can use different separators depending upon our use like : ‘\n’ for multiline string, ‘-‘ for dash between chars inside the string.

See the example code below,

# initialized a list of items with different data types.
example_list = ['Python','AI','ML','thispointer.com',2,7.8,91,'34']

# type() will print the data type of var example_list which happens to be be of class list.
print(type(example_list))

# joining all the items of list in string
new_str = ' '.join(str(item) for item in example_list)

# type() will print the data type of var new_str which happens to be of class str.
print(type(new_str))

print(new_str)

OUTPUT :

<class 'list'>
<class 'str'>
Python AI ML thispointer.com 2 7.8 91 34

In the above example, by using join() method with for loop and str() function, we have successfully joined all the items of a list into string. Also we have used ‘ ‘ i.e. a whitespace as a separator, which will create a string where all substrings from list are separated by a whitespace.

Method 3 : Using List Traversal

Another method that we can use to join a list of items with different types as string is the List Traversal.

What is the meaning of Traversing?

  • Traversing means visiting each nodes of a data structure. Here we will visit each items of the list.

So in this method, we traverse through the each items of the list and append that to a string variable. But first we need to convert it into string. For this we will use str() method. If we do not convert to string first, then this can throw an TypeError if there is any non string element in the list.

See the example code below,

# initialized a list of items with different data types.
example_list = ['Python','AI','ML','thispointer.com',2,7.8,91,'34']

# type() will print the data type of var example_list 
# which happens to be be of class list.
print(type(example_list))

# initialized an empty string
new_str = ''

# traversing through each items of list example_list.
for items in example_list:
    # storing each traversed item into new_str after 
    # converting it into string using str() method.
    if len(new_str) > 0:
        new_str += ' '    
    new_str += str(items)

# type() will print data type of var new_str 
# which happens to be of class str
print(type(new_str))

print(new_str)

OUTPUT :

<class 'list'>
<class 'str'>
Python AI ML thispointer.com 2 7.8 91 34

So in the above example, we have used List Traversing method to join all the items of list example_list into a string variable new_str.

Method 4 : Using List Comprehension

List Comprehension is another technique and shorter syntax through which we can join a list of items with different data types into string. It is a one line method with which we will be using join() method to join all the items and store them to a string. We will also be using str() to convert non-string items of list into string. See the example code below,

# initialized a list of items with different data types.
example_list = ['Python','AI','ML','thispointer.com',2,7.8,91,'34']

# type() will print the data type of var example_list 
# which happens to be be of class list.
print(type(example_list))

# Using List Comprehension to store items of list in new_str 
new_string = ' '.join([str(item) for item in example_list])

# type() will print data type of var new_string 
# which happens to be of class str
print(type(new_string))

print(new_string)

OUTPUT :

<class 'list'>
<class 'str'>
Python AI ML thispointer.com 2 7.8 91 34

So in above example, by using List Comprehension we have successfully created a new string variable new_string with all the items of list example_list. Even though list had items of different data type, we converted them to string type and joined them to create a single string.

Summary

So in this Python tutorial, we learned about four different method using which we can join a list of items of different types to a string in Python. You can always all the methods but the most easy to understand method with shorter syntax is List Comprehension method.

Also we have used Python 3.9.12 for writing example codes. Type python –version to check your python version. Always try to write example codes on your machine. Happy Coding.

Pandas Tutorials -Learn Data Analysis with Python

   

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top