w3resource

Python: Convert a given list of tuples to a list of strings using map function

Python map: Exercise-17 with Solution

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/map/python-map-exercise-17.php