Saturday, November 16, 2024
Google search engine
HomeLanguagesPython | List of tuples to String

Python | List of tuples to String

Many times we can have a problem in which we need to perform interconversion between strings and in those cases, we can have a problem in which we need to convert a tuple list to raw, comma separated string. Let’s discuss certain ways in which this task can be performed. 

Method #1: Using str() + strip() The combination of above functions can be used to solve this problem. In this, we just convert a list into string and strip the opening, closing square brackets of list to present a string. 

Step-by-step approach:

  • Initialize a list of tuples called “test_list”.
  • Print the original list for reference.
  • Convert the list of tuples to a string using the str() function.
  • Remove the square brackets from the string using the strip() method with the argument ‘[]’.
  • Store the resulting string in a variable called “res”.
  • Print the final string.

Python3




# Python3 code to demonstrate working of
# List of tuples to String
# using str() + strip()
 
# initialize list
test_list = [(1, 4), (5, 6), (8, 9), (3, 6)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# List of tuples to String
# using str() + strip()
res = str(test_list).strip('[]')
 
# printing result
print("Resultant string from list of tuple : " + res)


Output : 

The original list is : [(1, 4), (5, 6), (8, 9), (3, 6)]
Resultant string from list of tuple : (1, 4), (5, 6), (8, 9), (3, 6)

Time complexity: O(1) for initialization and printing original list, O(n) for converting list of tuples to string and printing result, where n is the length of the input list.
Auxiliary space: O(n) for creating the string representation of the input list, where n is the length of the input list.

Method #2: Using map() + join() This is yet another way in which this task can be performed. In this, we apply the string conversion function to each element and then join the tuples using join(). 

Step-by-step approach:

  • Initialize a list of tuples named test_list with four tuples.
  • Print the original list using the print() function with a string message and the str() function to convert the list to a string.
  • Convert the list of tuples to a string using the join() and map() functions.
    a. The map() function applies the str() function to each tuple element of the test_list.
    b. The join() function concatenates each tuple element with a “, ” separator.
    c. The result of join() and map() is stored in the variable named res.
  • Print the resultant string from the list of tuples using the print() function with a string message and the variable res.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# List of tuples to String
# using map() + join()
 
# initialize list
test_list = [(1, 4), (5, 6), (8, 9), (3, 6)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# List of tuples to String
# using map() + join()
res = ", ".join(map(str, test_list))
 
# printing result
print("Resultant string from list of tuple : " + res)


Output : 

The original list is : [(1, 4), (5, 6), (8, 9), (3, 6)]
Resultant string from list of tuple : (1, 4), (5, 6), (8, 9), (3, 6)

Time complexity: O(n), where n is the number of tuples in the list.
Auxiliary space: O(n), for the new string created by joining the tuples.

Method #3 : Another approach is to use a for loop to iterate over the elements in the list of tuples, convert each tuple to a string, and concatenate the strings together using the + operator. 

Below is the implementation:

Python3




test_list = [(1, 4), (5, 6), (8, 9), (3, 6)]
print("The original list is:", test_list)
 
res = ''
for tup in test_list:
    res += str(tup) + ', '
 
# remove the trailing ', '
res = res[:-2]
print("Resultant string from list of tuples:", res)


Output

The original list is: [(1, 4), (5, 6), (8, 9), (3, 6)]
Resultant string from list of tuples: (1, 4), (5, 6), (8, 9), (3, 6)

Time complexity: O(n), where n is the number of tuples in the list. 
Auxiliary space: O(m), where m is the total length of the string representation of the tuples in the list.

Method #4: Using list comprehension and join()

Use a list comprehension to iterate over each tuple in the list and convert it to a string using the str() function. The resulting list of strings is then joined using the join() method with ‘, ‘ as the separator. The resulting string is stored in the variable res and printed out.

Python3




# initialize list of tuples
test_list = [(1, 4), (5, 6), (8, 9), (3, 6)]
 
# using list comprehension to convert each tuple to a string, and join them with ', '
res = ', '.join([str(t) for t in test_list])
 
# print the resultant string
print("Resultant string from list of tuple : ", res)


Output

Resultant string from list of tuple :  (1, 4), (5, 6), (8, 9), (3, 6)

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

Method #5: Using a generator expression and join()

This method uses a generator expression instead of a list comprehension. This can be useful when dealing with large datasets as it avoids creating a new list in memory.

Follow the below steps to implement the above idea:

  • Use a generator expression to iterate through each tuple in the list, and convert it to a string using the str() function
  • Join the resulting list of strings with the separator ‘, ‘ using the join() method
  • Store the resulting string in a variable named res.
  • Print the resulting string using the print() function, along with a message indicating that it is the resultant string from the list of tuples.

Below is the implementation of the above approach:

Python3




# initialize list of tuples
test_list = [(1, 4), (5, 6), (8, 9), (3, 6)]
 
# using generator expression to convert each tuple to a string, and join them with ', '
res = ', '.join(str(t) for t in test_list)
 
# print the resultant string
print("Resultant string from list of tuple : ", res)


Output

Resultant string from list of tuple :  (1, 4), (5, 6), (8, 9), (3, 6)

Time complexity: O(n), where n is the number of tuples in the input list. 
Auxiliary space: O(1), because it does not create any new lists or data structures in memory.

Method #6: Using reduce() from functools module

The reduce() function takes a function and a sequence of values and returns a single value by applying the function cumulatively to the sequence’s items from left to right. In this case, the lambda function takes two tuples, converts them to strings, and concatenates them with a comma and a space.

Python3




from functools import reduce
 
test_list = [(1, 4), (5, 6), (8, 9), (3, 6)]
res = reduce(lambda x, y: str(x) + ', ' + str(y), test_list)
 
print("Resultant string from list of tuple: " + res)


Output

Resultant string from list of tuple: (1, 4), (5, 6), (8, 9), (3, 6)

Time complexity: O(n), where n is the number of tuples in the list. This is because the reduce() function iterates over each tuple in the list once.
Auxiliary space: O(1), which is constant space. This is because the reduce() function only stores the intermediate results (i.e., the concatenated string) and not the entire list of tuples or any other additional data structure.

Method #7: Using  numpy():

Algorithm:

  1. Import the NumPy module as np.
  2. Create a list of tuples named test_list.
  3. Convert the test_list to a NumPy array using the np.array() method and assign it to the res_arr variable.
  4. Convert the res_arr NumPy array to a string using the np.array2string() method and assign it to the res_str variable.
  5. Print the resultant string.
     

Python3




import numpy as np
 
test_list = [(1, 4), (5, 6), (8, 9), (3, 6)]
print("The original list is:", test_list)
  
res_arr = np.array(test_list)
res_str = np.array2string(res_arr, separator=', ')
print("Resultant string from list of tuple: " + res_str)
#This code is contributed by Rayudu.


Output:

The original list is: [(1, 4), (5, 6), (8, 9), (3, 6)]
Resultant string from list of tuple: [[1, 4],
[5, 6],
[8, 9],
[3, 6]]

Time complexity:

Creating a list of tuples takes O(n) time complexity, where n is the number of tuples in the list.
Converting the list to a NumPy array takes O(n) time complexity as well.
Converting the NumPy array to a string takes O(1) time complexity.
Thus, the overall time complexity of the algorithm is O(n).
Space complexity:

The space complexity of the algorithm is O(n) as we are storing the list of tuples in memory as well as the NumPy array. The space required for the resultant string is negligible compared to the size of the input list.

RELATED ARTICLES

Most Popular

Recent Comments