w3resource

Python: Convert string element to integer inside a given tuple using lambda


Write a Python program to convert string elements to integers inside a given tuple using lambda.

Sample Solution:

Python Code :

# Define a function 'tuple_int_str' that converts specific elements in a tuple of strings to integers
def tuple_int_str(tuple_str):
    # Use 'map' with a lambda to convert the first and third elements in each tuple of 'tuple_str' to integers
    # The lambda function takes each tuple 'x' and extracts the first and third elements, converting them to integers
    # Create a new tuple containing these converted elements
    result = tuple(map(lambda x: (int(x[0]), int(x[2])), tuple_str))
    
    # Return the new tuple containing integer values
    return result

# Create a tuple of tuples 'tuple_str' containing string elements
tuple_str =  (('233', 'ABCD', '33'), ('1416', 'EFGH', '55'), ('2345', 'WERT', '34'))

# Print the original tuple values 'tuple_str'
print("Original tuple values:")
print(tuple_str)

# Call the 'tuple_int_str' function to convert specific elements to integers and print the new tuple values
print("\nNew tuple values:")
print(tuple_int_str(tuple_str))

Sample Output:

Original tuple values:
(('233', 'ABCD', '33'), ('1416', 'EFGH', '55'), ('2345', 'WERT', '34'))

New tuple values:
((233, 33), (1416, 55), (2345, 34))

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to calculate the average value of the numbers in a given tuple of tuples using lambda.

Next: Write a Python program to find index position and value of the maximum and minimum values in a given list of numbers using lambda.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.