How to Convert List to String in Python?
Updated on Oct 06, 2022 | 7 min read | 6.1k views
Share:
For working professionals
For fresh graduates
More
Updated on Oct 06, 2022 | 7 min read | 6.1k views
Share:
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! If you are a beginner in python and data science, upGrad’s data science certification. can definitely help you dive deeper into the world of data and analytics.
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. If you want to learn more about python, you will find our data science programs useful.
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, 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.
Python gives you four methods for converting your lists into strings. Here are those methods:
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’
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?
The map() function can be used in either of the two cases:
Further, the map() function works by accepting two arguments:
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
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
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.
If this data science career aligns with your interests, we recommend you acquire an 18-month Master’s of Science in Data Science to land job opportunities on the global platform. upGrad offers you the chance to pursue your education online from the renowned Liverpool John Moores University while continuing your work commitments. The comprehensive course is designed for students interested in Natural Language Processing, Deep Learning, Business Analytics, Business Intelligence/Data Analytics, Data Engineering, and Data Science Generalist.
With the dedicated guidance of our expert mentors, you will become a job-ready candidate for trending jobs across industries.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources