How to usereduce() function in Python
We can use reduce() function to combine the first and last name of each tuple record in the given list of tuples.
Algorithm:
- Import the reduce() function from the functools module.
- Define a lambda function that takes two arguments and concatenates them with a space in between.
- Pass the lambda function and the list of tuples to the reduce() function.
- Join the resulting list of names with a comma and a space in between.
Python3
from functools import reduce # Initializing list test_list = [( 'Manjeet' , 'Singh' ), ( 'Nikhil' , 'Meherwal' ), ( 'Akshat' , 'Garg' )] # printing original list print ( "The original list is : " + str (test_list)) # Using reduce() function to combine the first and last name of each tuple record res = reduce ( lambda x, y: x + ', ' + y, [name[ 0 ] + ' ' + name[ 1 ] for name in test_list]) # 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)
Auxiliary space: O(n)
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