How to use a simple for loop In Python

This code initializes an empty string res and iterates through each tuple in the list test_list. For each tuple, it adds the first and last name to res, along with a comma and space. Finally, it removes the last comma and space from res. The result is the same as the one obtained using the map() and join() methods.

Python3




# Initializing list
test_list = [('Manjeet', 'Singh'), ('Nikhil', 'Meherwal'), ('Akshat', 'Garg')]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Convert tuple records to a single string using a for loop
res = ""
for tuple in test_list:
    res += tuple[0] + " " + tuple[1] + ", "
 
# remove the last comma and space
res = res[:-2]
 
# printing result
print("The string after tuple conversion: " + res)


Output

The original list is : [('Manjeet', 'Singh'), ('Nikhil', 'Meherwal'), ('Akshat', 'Garg')]
The string after tuple conversion: Manjeet Singh, Nikhil Meherwal, Akshat Garg

Time complexity: O(n), where n is the number of tuples in the test_list. 
Auxiliary space: O(m), where m is the length of the resulting string res.

Python | Convert tuple records to single string

Sometimes, while working with data, we can have a problem in which we have tuple records and we need to change it’s to comma-separated strings. These can be data regarding names. This kind of problem has its application in the web development domain. Let’s discuss certain ways in which this problem can be solved

Similar Reads

Method #1: Using join() + list comprehension

In this method, we just iterate through the list tuple elements and perform the join among them separated by spaces to join them as a single string of records....

Method #2: Using map() + join()

...

Method #3 : Using join() and replace() methods

This method performs this task similar to the above function. The difference is just that it uses map() for extending join logic rather than list comprehension....

Method #4 : Using a format():

...

Method 5: Using a simple for loop:

Python3 # Python3 code to demonstrate working of # Convert tuple records to single string   # Initializing list test_list = [('Manjeet', 'Singh'), ('Nikhil', 'Meherwal'), ('Akshat', 'Garg')]   # printing original list print("The original list is : " + str(test_list))   # Convert tuple records to a single string res = [] for i in test_list:     x = " ".join(i)     res.append(x) res = str(res) res = res.replace("[", "") res = res.replace("]", "") # printing result print("The string after tuple conversion: " + res)...

Method 6: Using reduce() function

...

Contact Us