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:

  1. Import the reduce() function from the functools module.
  2. Define a lambda function that takes two arguments and concatenates them with a space in between.
  3. Pass the lambda function and the list of tuples to the reduce() function.
  4. 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

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

...