Programs

How to Convert List to String in Python?

Python is a highly versatile programming language, especially when it comes to solving data-related problems and challenges. The reason for this is that Python comes with many libraries, data structures, and in-built functions that help manipulate and analyze large volumes of complex data. 

Strings and lists are two such data structures frequently used in the Python programming language to manipulate a collection of data. Through this article, let’s understand the finer differences between lists, strings, and the methods for converting lists to strings in Python! 

Lists in Python

If you have worked with any programming language, like C, Java, C++, you would already know about the concept of arrays. Lists are pretty similar to arrays, except that lists can contain any data type as its elements, unlike arrays. By definition, a list in Python is a collection of objects that are ordered. Like arrays, indexing in lists is also done in a definite sequence, with 0 being the first index. The lists in Python are known as “collection data type” and can contain integers, float values, strings, or even other lists. By nature, lists are mutable, i.e., you can change them even after their creation. 

The important point to note about lists in Python is that they can contain duplicate entries, unlike sets. You can create lists in Python using the following manner: 

Program:

BlankList=[] #This is an empty list

NumbersList=[1,2,36,98] #This is a list of numbers

ObjectsList=[1,”a”,[“list”,”within”, “another”, “list”],4.5] # List containing different objects

print(BlankList)

print(NumbersList)

print(ObjectsList)

Output:

[]

[1, 2, 36, 98]

[1, ‘a’, [‘list’, ‘within’, ‘another’, ‘list’], 4.5]

Strings in Python

Strings, in Python, are one of the primary data types and can be defined as a sequence or collection of different characters. Python provides you with a built-in class – ‘str’ – to handle strings in Python. Creating and initializing strings in Python is as simple as initializing any other variables. Here is the syntax for that: 

Program: 

first_name= “Sherlock”

last_name=”Holmes”

print(first_name, last_name)

string1 = “this is a string with double-quotes.”

string2 = ‘this is a string with single quotes.’

string3 = ‘’’this is a string with triple quotes.’’’

print(string1)

print(string2)

print(string3)

Output:

Sherlock Holmes

this is a string with double-quotes.

this is a string with single quotes.

this is a string with triple quotes.

As you can see, Python allows you to create strings using ways – using single quotes, double-quotes, and triple quotes. However, single or double-quotes are more preferred over triple quotes to create strings in Python. 

What happens when the string itself contains quotes? Let us check that with some examples: 

Example 1) string = “Hello “Python””

SyntaxError: bad input on line 1

1>: thon” “

Here, we have used double-quotes to create the string, but the string itself contains the word Python in double-quotes. As a result, Python throws an error. So, the best way to go about this would be initializing the string using single quotes if the string already contains double quotes within it. 

Example 2) string =’Hello “Python”‘

print(string)

Hello “Python”

As you can see, this line of code executes perfectly, and we get Hello “Python” as our output. This is because here, we used single quotes to create the string.

Example 3) string = ‘Let’s go to the park’

SyntaxError: bad input on line 1

1>: to the park

Similar to the first example, this string will also give an error in Python because of the ambiguity of single and double quotes. 

Example 4) string =”Let’s go to the park”

print(string)

Let’s go to the park

This code gets executed without any issues! 

Example 5) string = ”’Let’s go the “PARK””’

print(string_3)

Let’s go the “PARK

Here, too, the code executes properly, and we get the desired output. While creating strings in Python, you should try to avoid any ambiguities that might arise due to single, double, or triple quotes in the string. 

Now, let’s talk about how to convert lists to strings in Python!

Also check out Python Cheat Sheet.

Converting Lists to Strings in Python

Python gives you four methods for converting your lists into strings. Here are those methods: 

1. Using Join Function

Using a join function is one of the easiest ways to convert a Python list into a string. However, one thing to note before using this method is that the joint function can convert only those lists that contain ONLY strings as their elements. 

Check out the following example: 

list = [‘hello’, ‘how’, ‘are’, ‘you’]

‘ ‘.join(list)

Output:

‘hello how are you’

Since all the elements of the list were strings, we simply used the join function and converted the entire list into a larger string. 

Now, in case your list contains elements other than just strings, you can use the str() function to first convert all the other data types into a string, and then the join function will be used to convert it into an entire string.

list = [1,2,3,4,5,6]

‘ ‘.join(str(e) for e in list)

Output:

‘1 2 3 4 5 6’

2. Traversing the List Function

In this method, first, a list is created and is then converted into a string. Then, we initialize an empty string to store the elements of the list. After that, we traverse through each of the list elements, using a for loop, and for every index, we add the element to the required string. Then, using the print() function, we can print the final converted string. Here is how that is done: 

list = [‘how’, ‘are’, ‘you’, ‘?’]

mystring = ‘ ‘

for x in list: 

mystring += ‘ ‘ + x

print(mystring)

Output: 

how are you? 

3. Using Map Function

The map() function can be used in either of the two cases:

  • Your list contains only numbers.
  • Your list is heterogeneous. 

 Further, the map() function works by accepting two arguments: 

  • str() function — this is required to convert the given data type into string type. 
  • An iterable sequence — every element of this sequence will be called by str() function. 

In the end, the join() function is again used to combine all of the values returned by the str() function. 

list = [‘how’, ‘are’, ‘you’, ‘?’, 1, 2, 3]

mystring = ‘ ‘.join(map(str,list))

print(mystring)

Output:

hello how are you ? 1 2 3

4. List Comprehension

List comprehension in Python creates a list of elements from an existing list. Then, it uses the for loop to traverse all the iterable objects in an element-wise pattern. 

Python list comprehension and join() function are used together to convert a list into a string. The list comprehension traverses all the elements one by one, while the join() function concatenates the list elements into a string and gives it as output. 

Check the following example for conversion of list to string using list comprehension method: 

start_list = [‘using’, ‘list’, ‘comprehension’]

string = ‘ ‘.join([str(item) for item in start_list])

print(“converting list into string \n”)

print(string)

Output:

converting list to string

using list comprehension

In Conclusion

We saw four methods for converting lists into strings. You can either use the join() function, traversal of the list, map() function, or list comprehension to change any list of your choice into a string. We hope this article helped you get behind the nuances of strings and lists manipulation in Python. 

If you still feel confused, reach out to us! At upGrad, we have successfully mentored students from around the globe, in 85+ countries, with 40,000+ paid learners globally, and our programs have impacted more than 500,000 working professionals. Data Science Courses and Machine Learning courses have been designed to teach learners everything, starting from the basics to advanced levels. With the dedicated guidance of our expert mentors, you will become a job-ready candidate for trending jobs across industries.

What are lists in Python?

Lists is a collection data structure in Python that is homogeneous in nature - that is, they can store elements of different data types.

What are the ways in which lists in Python can be converted to strings?

There are broadly 4 ways in which you can convert lists to strings in Python:
1. Using join function
2. Traversing the list function
3. Using map function
4. List comprehension

Why do we need to convert lists into strings?

For data manipulation and storage, it is good advice to convert lists into strings if you don’t require to work with the list data structure as such.

Plan Your Data Science Career Today

Become a Data Scientist with upGrad and IIIT Bangalore
Apply Now

0 replies on “How to Convert List to String in Python?”

Accelerate Your Career with upGrad

Our Best Data Science Courses

×