Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Python Program to Convert a List to String

Last Updated on March 16, 2023 by Prepbytes

In this article, we’ll cover several techniques for the conversion of a python list to a string, Python is one of the most widely used programming languages today. Along with this, we will also talk about Python’s subtleties, such as what a list and a string are in python. Let’s learn about lists and strings first before delving into the variety of ways we could do this.

What is a List in Python?

In Python, a list is an ordered sequence that can contain several sorts of objects, including integers, characters, and floats. In other programming languages, an array is the counterpart of a list. Square brackets are used to denote it, and two items in the list are separated by commas (,).

The difference between a list and an array in other programming languages is that an array only stores data types that are similar, making it homogeneous in nature, whereas a list in Python can store multiple data types at once, making it either homogeneous or heterogeneous. Here are a few Python homogeneous and heterogeneous list examples:

Homogenous Lists

l = [1, 2, 3, 4, 5]
l = ["dog", "cat"]
l = ["a", "b", "c"]

Heterogeneous Lists

l = [1, "dog", 2.2, "a"]

Accessing an Item From the List

l = [1, "dog", 2.2, "a"]
print(l[1])

Output

dog

By using the item’s index within the list, a specific item from the list can be reached. The list’s items are indexed starting at zero. Take a look at an example from the list we made in the previous phase.

We supply the index of the desired element to the print function in order to get it from the list.

As was previously established, since indexing begins at 0, the result is "dog" when index [1] is passed. Similarly to that, if we pass an index, like [2], it will produce 2.2.

What is a String in Python?

Python defines a string as an organized collection of characters. A list is an ordered sequence of different object kinds, whereas a string is an ordered sequence of characters. This is important to keep in mind. This is the key distinction between the two.

Several pieces of the same data type, such as an integer, float, character, etc., make up a sequence, which is a type of data. This implies that a string, which contains all items as characters, is a subset of the sequence data type.

Let’s see a Python string sample and instructions on how to print it.

s = "PrepBytes"
print(s)

Output

PrepBytes

We assign a variable to the string when declaring it. Here, the string PrepBytes is a variable named s. The same method we used to access a list’s elements also applies to accessing a string’s elements. A string’s element indexing likewise begins at 0.

Instructions to convert List to String in Python

Let’s explore different methods for converting a python list to a string.

Method 1: Go through the list iteratively, adding an element for each index of a blank 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 = ['Learn', 'To', 'Code']
print(listToString(s))

Output

LearnToCode

Time Complexity: O(n) will be the time complexity for python list to string conversion.
Auxiliary Space: O(n) will be the time complexity for python list to string conversion.

Method 2: Using the .join() method, for the conversion of the python list to a string

def listToString(s):
   
    # initialize an empty string
    str1 = " "
   
    # return string 
    return (str1.join(s))
       
       
# Driver code   
s = ['Learn', 'To', 'Code']
print(listToString(s))

Output

LearnToCode

But what if the list’s elements are both strings and integers? The code above won’t function in some situations. By adding to string, we must convert it to string.

Method 3: Using list comprehension, for the conversion of python list to string

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

Method 4: Using the map() method, for the conversion of the python list to a string
Use the map() method to map the provided iterator, the list, to str (to convert list elements to string).

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

Method 5: Using enumerate function, for the conversion of the python list to a string

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

Method 6: Using in operator, for the conversion of python list to string

s = ['Learn', 'To', 'Code']
for i in s:
  print(i,end=" ")

Output

Learn To Code

Method 7: Using functools.reduce method, for the conversion of python list to string

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

Method Bonus: Using the str.format method, for the conversion of the python list to string

Using Python’s str.format method is an additional method to turn a list into a string. With the help of the elements in the list, you may fill in the blanks in the string template that you define using this technique.

For example:

lst = ['Learn', 'To', 'Code']
 
# Convert the list to a string using str.format
result = "{} {} {}".format(*lst)
 
print(result)  # Output: Learn To Code

Output

Learn To Code

By utilizing the formatting placeholders in the string template, this method has the advantage of allowing exact formatting instructions for the list’s elements. For instance, you can choose the width and alignment of the output string or the number of decimal places for floating point figures.

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

Output

1.23 good 3.46

The length of the list will determine how time-consuming the aforementioned strategies are. For instance, approach 1’s time complexity will be O(n), where n is the list’s length because we are iterating through the list and adding each member to a string.

Corresponding to this, other approaches’ time complexity will also be O (n).

Due to the fact that we are establishing a new string of size n to hold the list’s elements, all of the aforementioned approaches will likewise have an O(n) space complexity.

Method 8: Using Recursion, for the conversion of a python list to a string

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=['Learn', 'To', 'Code']  #defining list
print(list_string(0,l,''))

Output

Learn To Code

Conclusion
Here we have discussed various ways the conversion of Python list to a string. Besides the ways discussed here, there are plenty of more solutions for the same problem, by practicing more and deep diving into python you will definitely figure it out. Also, there are a few points that should be remembered:

  • In Python, a list is a mutable data type that is employed to store things. In contrast to other programming languages, lists allow for the storage of objects of various data kinds.
  • An immutable data type is a string. They are indexed similarly to lists, beginning at 0.
  • This method can be used to access any element of a string or list: For the first element of the list, use list[0], and for the fourth member, use string[3].

FAQ Related to Python List To String Conversion

1. How can I make a Python string into a list that resembles a list?
The Python split() function is another approach to turning a string into a list. A string is divided into a list by the split() method, where each list item represents a word in the original string. There will be a separate list item for each word.

2. How can I convert a list in Python to an array?
In Python, there are three ways to turn a list into an array: using the array(), the numpy array(), or the numpy asarray().

3. How do you change a list in Python into an integer?
Using the list comprehension [int(x) for x in strings] is the most Pythonic technique to change a list of strings into a list of ints. Every element in the list is iterated over, and the built-in function int(x) is used to convert each element from the list to an integer value.

4. Are string and list equivalent?
A string is a group of letters or numbers enclosed in single or double quotations. A list is a collection of objects, each of which could be anything (an integer, a float, a string, etc).

5. How do I convert a Python int to a string?
The built-in function str() can be used to convert an integer to a string. The function outputs a string and accepts an integer (or another type) as input.

6. Can a list be changed into a set?
By inserting the list name between the necessary parentheses when using the set() command, we may convert a list into a set. In order to turn the names in the list into a set in the example above, we must type the set(the names).

Leave a Reply

Your email address will not be published. Required fields are marked *