Python | Convert Tuple to integer

Sometimes, while working with records, we can have a problem in which we need to convert the data records to integer by joining them. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using reduce() + lambda
The combination of above functions can be used to perform this task. In this, we use lambda function to perform logic of conversion and reduce performs task of iteration and combining result.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Convert Tuple to integer
# Using reduce() + lambda
import functools
  
# initialize tuple
test_tuple = (1, 4, 5)
  
# printing original tuple 
print("The original tuple : " + str(test_tuple))
  
# Convert Tuple to integer
# Using reduce() + lambda
res = functools.reduce(lambda sub, ele: sub * 10 + ele, test_tuple)
  
# printing result
print("Tuple to integer conversion : " + str(res))

chevron_right


Output :

The original tuple : (1, 4, 5)
Tuple to integer conversion : 145

 

Method #2 : Using int() + join() + map()
The combination of these functions can also be used to perform this task. In this, we convert each element to string using join() and iterate using map(). At last we perform integer conversion.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Convert Tuple to integer
# Using int() + join() + map()
  
# initialize tuple
test_tuple = (1, 4, 5)
  
# printing original tuple 
print("The original tuple : " + str(test_tuple))
  
# Convert Tuple to integer
# Using int() + join() + map()
res = int(''.join(map(str, test_tuple)))
  
# printing result
print("Tuple to integer conversion : " + str(res))

chevron_right


Output :

The original tuple : (1, 4, 5)
Tuple to integer conversion : 145



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.