Concatenate items in a List to a String

In this article, you will learn to concatenate items in list to a single string object in Python.

Table Of Contents

What are Strings and List ?

Strings

A String in python is an array of bytes representing Unicode characters enclosed in single, double or triple quotes.

List

Advertisements

A List in Python is a kind of container enclosed in a square bracket that can hold data of any data type like integers or string etc. For better understanding, consider that list in python is simmilar to an array in other programming languages but here is one big difference i.e. – An array in other programming language stores similar kind of data type but a list can store elements of mixed data types. Therefore it is also known as Heterogeneous List.

Major difference between a list and a string is that a list is an ordered sequence of differet kinds of objects and a string is an ordered sequence of characters.

Now we will look some of the methods through which we can concatenate items in a list to a single string.

Always try examples in your machine.Just copy and paste code and play around with it. Also i have used Python 3.10.1 for writing example codes. To check your version write python –version in your terminal.

Concatenate items in a list to a string using For Loop

For loop in python is used to iterate over elements of a given sequence type (list or tuple etc). Here we will initialize an empty string and add elements of list after iterating over it. Keep in mind it can cannot concatenate a Heterogeneous List, because it will throw a TypeError. It only concatenates a list of strings to a string.

EXAMPLE :

listOfStrs = ['Concatenating', 'using', 'Loop']

strValue = ''

# Concatenate strings in a list to a single string
for elem in listOfStrs:
    sep = ' ' if len(strValue) > 0 else ''
    strValue = strValue + sep + elem

print(strValue)

OUTPUT :

Concatenating using Loop

Here you can see elements of list has been concatenated into a single string.

Concatenate items in a list to a string using join()

The join() method is a built in python function which takes only one parameter, that is an iterable. It joins all elements in this iterable to a string.We can use this to Concatenate all elements in a list to a string.

EXAMPLE :

listOfStrs = ['Concatenating','using','join','method']

# Concatenate strings in a list to a single string
strValue = ' '.join(listOfStrs)

print(strValue)

OUTPUT :

Concatenating using join method

Here you can see items in listOfStrs has been concatenated into a string using the join() method.

Concatenate items in a list to a string using map() method :

The map() is a built-in function of Python, and it is used to apply a function to each time in an iterable. It recieves two parameters i.e. a function and an iterable.

SYNTAX :

map(function, iterable) 

Using map() function becomes very useful when we have either Heterogeneous list or a list of integers.

Here map() function will get two arguments –
str() function : The str() function will convert the given data into string.
– A list, which we want to convert into a string.

At last we will use the join() function to combine the returned data from above function. This method is combination of various methods like str(), join() , map(), but can be most useful method.

EXAMPLE :

listOfValues = ["Highest","Score","Of","MSD","is",183,"in","ODI","cricket"]

strValue = ' '.join(map(str, listOfValues))

print(strValue)

OUTPUT :

Highest Score Of MSD is 183 in ODI cricket

Here you can see items of heterogenous list(listOfValues) has been concatenated into a string variable(strValue) using map() and there is not any kind of Error.

Concatenate items in a list to a string using reduce()

Apply str() function on each element of list to convert them to string. Then pass that sequence to reduce() function along with a lambda function that will concatenate the strings.

For Example

from functools import reduce

listOfValues = ["Highest", "Score", "Of", "MSD", "is", 183, "in", "ODI", "cricket"]

# Concatenate all items in list to a string
strValue = reduce(lambda x,y: x + ' ' + y, map(str, listOfValues) )

print(strValue)

Output

Highest Score Of MSD is 183 in ODI cricket

Summary

So we have seen three different methods through which we can concatenate items in a list to a single string. Most easiest method is join() method and most practical and useful method is map() method because there is no barrier of using only one kind of data. You can use int or combination of string,int and float. You cannot use any other data type in other two methods because it will genarate a TypeError. Like you can see in the example below.

CODE :

ex_lst = ["Highest","Score","Of","MSD","is",183,"in","ODI","cricket"]

ex_str = ' '.join(ex_lst)

print(ex_str)

OUTPUT :

    ex_str = ' '.join(ex_lst)
TypeError: sequence item 5: expected str instance, int found

Thanks and Happy Learning.

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