Python: Convert a given list of tuples to a list of strings using map function
Write a Python program to convert a given list of tuples to a list of strings using the map function.
Sample Solution:
Python Code:
# Define a function named 'tuples_to_list_string' that takes a list of tuples as input
def tuples_to_list_string(lst):
# Use the 'map' function with 'join' to concatenate elements within each tuple using a space as a separator
# Convert the map object to a list and return the result
result = list(map(' '.join, lst))
return result
# Define a list of tuples named 'colors'
colors = [('red', 'pink'), ('white', 'black'), ('orange', 'green')]
# Print a message indicating the operation to be performed
print("Original list of tuples:")
# Print the original list of tuples
print(colors)
# Print a newline for better readability
print("\n")
# Print a message indicating the operation to be performed
print("Convert the said list of tuples to a list of strings:")
# Print the result of calling the 'tuples_to_list_string' function with the 'colors' list
print(tuples_to_list_string(colors))
# Define another list of tuples named 'names'
names = [('Sheridan', 'Gentry'), ('Laila', 'Mckee'), ('Ahsan', 'Rivas'), ('Conna', 'Gonzalez')]
# Print a newline for better readability
print("\n")
# Print a message indicating the operation to be performed
print("Original list of tuples:")
# Print the original list of tuples
print(names)
# Print a newline for better readability
print("\n")
# Print a message indicating the operation to be performed
print("Convert the said list of tuples to a list of strings:")
# Print the result of calling the 'tuples_to_list_string' function with the 'names' list
print(tuples_to_list_string(names))
Sample Output:
Original list of tuples: [('red', 'pink'), ('white', 'black'), ('orange', 'green')] Convert the said list of tuples to a list of strings: ['red pink', 'white black', 'orange green'] Original list of tuples: [('Sheridan', 'Gentry'), ('Laila', 'Mckee'), ('Ahsan', 'Rivas'), ('Conna', 'Gonzalez')] Convert the said list of tuples to a list of strings: ['Sheridan Gentry', 'Laila Mckee', 'Ahsan Rivas', 'Conna Gonzalez']
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to convert a given list of strings into list of lists using map function.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics