A list in Python is used to hold multiple data items, which can be of different data types. It can be
Lists can be converted to strings using some techniques. In this shot, we will learn three different ways of doing this.
Create an empty string, iterate over the items in the list using their index, and then add each iterated item of the list to the empty string.
In the code below, the list
alist was looped through with each item added to the initially empty string
strings. The function
convert() handles this looping, and at the end of the code, the function is called and its output is printed to the screen.
# Function that handles the conversion def convert(alist): # the empty string is declared and initialized strings = " " # loop through the list item for items in alist: strings += items # return the new string return strings # call the convert function alist = ['Edpresso ','byte ', 'sized ', 'shots '] print(convert(alist))
In this second method, two Python functions,
map(), were combined to achieve our conversion.
In the below code snippet, the
map() function iteratively maps each item in the list
alist and readies them for insertion into a string. The
join() function will now join the string object returned by the map function to the empty
strings variable already declared.
The converted string is saved in
alistConv and printed to the screen.
# a list is defined alist = ['Edpresso ', 9 ,'ice','platform',4 ,'byte ', 'sized ', 'shots '] # an empty string is initialized strings = ' ' # alistConv variable saves the output alistConv = strings.join(map(str, alist)) # print result to screen print(alistConv)
In this method, the
join() function will be used alone without
map(). This contrasts with method 2, where the
map() function served as the iterator. Here, a function that returns the converted code will be used.
# Function that handles the conversion def liststr(somelist): # the empty string is declared and initialized strings = " " # return the new string return strings.join(somelist) # call the convert function somelist = ['Edpresso ','byte ', 'sized ', 'shots '] print(liststr(somelist))
In this last code example, the
join() function performs a join operation on the items in the list by removing the items from the quotation marks and returning the space-separated list items in the empty string variable created earlier.
And with that, we have three simple and easy list to string conversion methods.
View all Courses