Wednesday, December 25, 2024
Google search engine
HomeLanguagesPython Program to Convert a List to String

Python Program to Convert a List to String

Given a list, write a Python program to convert the given list to a a string. There are various situations we might encounter when a list is given and we convert it to a string in Python.

For example, conversion to a string from a list of strings or a list of integers. 

Example

Input: ['Geeks', 'for', 'Geeks']
Output: Geeks for Geeks
Explanation: The Input is of list data type but the output is of string datatype

Program to Convert a List to a String

Convert Python List to String using for loop

Iterate through the list using for loop and keep adding the element for every index in some empty string and that is how the final string we have will be of string datatype

Python3




# Python program to convert a list to string
 
def listToString(s):
 
    # initialize an empty string
    str1 = ""
 
    # traverse in the string
    for ele in s:
        str1 += ele
 
    # return string
    return str1
# Driver code
s = ['Geeks', 'for', 'Geeks']
print(listToString(s))


Output

Lazyroar


Time Complexity: O(n)
Auxiliary Space: O(n)

Convert Python List to String using .join() method 

Function listToString(s) that takes a list s as input. Inside the function, an empty string str1 is initialized. The .join() function then returns the result of joining the elements of the input list s into a single string using the space character as a separator. The driver code initializes a list s, calls the function listToString(s), and prints the result of joining the list elements with spaces.

Note: But what if the list contains both string and integer as its element? In those cases, the above code won’t work. We need to convert it to string while adding to string. 

Python3




# Function to convert
def listToString(s):
 
    # initialize an empty string
    str1 = " "
 
    # return string
    return (str1.join(s))
     
     
# Driver code
s = ['Geeks', 'for', 'Geeks']
print(listToString(s))


Output

Geeks for Geeks


Time Complexity: O(n)
Auxiliary Space: O(n)

Convert a List to a String using list comprehension 

Here we are going to use list comprehension to convert a list to a string as the below code shows the implementation

Python3




# Python program to convert a list to string using list comprehension
s = ['I', 'want', 4, 'apples', 'and', 18, 'bananas']
 
# using list comprehension
listToStr = ' '.join([str(elem) for elem in s])
 
print(listToStr)


Output

I want 4 apples and 18 bananas


Time complexity: The time complexity of the program is O(n), where n is the length of the list s, because it iterates over each element of the list once.
Space complexity: The auxiliary space complexity of the program is O(n) because it creates a new list of strings using a list comprehension.

Convert a List to a String using the map() function

Use the map() method for mapping str (for converting elements in the list to string) with the given iterator, the list. As shown below code is the implementation by using the map() function

Python3




# Python program to convert a list to string using list comprehension
  
s = ['I', 'want', 4, 'apples', 'and', 18, 'bananas']
 
# using list comprehension
listToStr = ' '.join(map(str, s))
 
print(listToStr)


Output

I want 4 apples and 18 bananas


Time complexity: The time complexity of this code is O(n), where n is the length of the list s. 
Space complexity: The space complexity of this code is O(n), where n is the length of the list s.

List to String using enumerate function

The code converts the elements of the list s into a single string, separating them with spaces. It iterates over the elements of s, converts each element to a string, and joins them using a space separator. The resulting string is then printed.

Python3




s = ['I', 'want', 4, 'apples', 'and', 18, 'bananas']
 
listToStr = ' '.join([str(elem) for i,elem in enumerate(s)])
 
print(listToStr)


Output

I want 4 apples and 18 bananas


Time Complexity: O(n)
Auxiliary Space: O(n)

List to a String using in operator

The code iterates over each element i in the list s and prints it. The end=” ” specifies that a space should be printed after each element instead of a newline character, resulting in the elements being printed on the same line separated by spaces.

Python3




s = ['Geeks', 'for', 'Geeks']
for i in s:
  print(i,end=" ")


Output

Geeks for Geeks 


Time Complexity: O(n)
Auxiliary Space: O(n)

Convert a List to Using functools.reduce method

The code uses the reduce() function from the functools module to combine the elements of the list s into a single string. It applies the lambda function lambda a, b: a + ” ” + str(b) to sequentially concatenate each element b with the previous result a. The resulting string is then printed.

Python




from functools import reduce
s = ['I', 'want', 4, 'apples', 'and', 18, 'bananas']
 
listToStr = reduce(lambda a, b : a+ " " +str(b), s)
 
print(listToStr)


Output

I want 4 apples and 18 bananas


Time complexity: The time complexity of the provided Python code is O(n), where n is the number of elements in the input list
Space complexity: The space complexity of the code is O(n), where n is the number of elements in the input list s. 

List to String using str.format method

One additional approach to convert a list to a string in Python is to use the str.format method. This method allows you to specify a string template, and then fill in the placeholder values with the elements in the list.

For example:

Python3




lst = ['Geeks', 'for', 'Geeks']
 
# Convert the list to a string using str.format
result = "{} {} {}".format(*lst)
 
print(result)  # Output: Geeks for Geeks
#This code is contributed by Edula Vinay Kumar Reddy


Output

Geeks for Geeks


This approach has the advantage of being able to specify exactly how the elements in the list should be formatted, by using the formatting placeholders in the string template. For example, you can specify the number of decimal places for floating point numbers, or the width and alignment of the output string.

Python3




lst = [1.2345, 'good' , 3.4567]
 
# Convert the list to a string using str.format
result = "{:.2f} {} {:.2f}".format(*lst)
 
print(result)  # Output: 1.23 2.35 3.46
#This code is contributed by Edula Vinay Kumar Reddy


Output

1.23 good 3.46


Time complexity: The time complexity of the above approaches will depend on the length of the list. For example, in method 1, we are iterating through the list and adding each element to a string, so the time complexity will be O(n), where n is the length of the list.
Similarly, the time complexity of other methods will also be O(n).
Space complexity: The space complexity of all the above methods will also be O(n) as we are creating a new string of size n to store the elements of the list.

Convert Python List to String using Recursion 

The code recursively converts a list l into a string word by concatenating its elements. It starts from the start index, appends the current element to the word, and continues the process until reaching the end of the list. The resulting string is then printed.

Python3




def list_string(start, l, word):
    if start == len(l):
        return word  # base condition to return string
    word += str(l[start])+' '  # concatenating element in list to word variable
    return list_string(start+1, l, word)  # calling recursive function
 
 
# Driver code
l = ['Geeks', 'for', 'Geeks'# defining list
print(list_string(0, l, ''))


Output

Geeks for Geeks 


RELATED ARTICLES

Most Popular

Recent Comments