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) |
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