Python | Convert list of tuples into digits
Given a list of tuples, the task is to convert it into list of all digits which exists in elements of list.
Let’s discuss certain ways in which this task is performed.
Method #1: Using re
The most concise and readable way to convert list of tuple into list of all digits which exists in elements of list is by using re.
# Python code to convert list of tuples into# list of all digits which exists# in elements of list. # Importingimport re # Input list initializationlst = [(11, 100), (22, 200), (33, 300), (44, 400), (88, 800)] # Using retemp = re.sub(r'[\[\]\(\), ]', '', str(lst)) # Using setOutput = [int(i) for i in set(temp)] # Printing outputprint("Initial List is :", lst)print("Output list is :", Output) |
Initial List is : [(11, 100), (22, 200), (33, 300), (44, 400), (88, 800)]
Output list is : [1, 4, 8, 0, 3, 2]
Method #2: Using itertools.chain() and lambda()
This is yet another way to perform this particular task using lambda().
# Python code to convert list of tuples into# list of all digits which exists# in elements of list. # Importingfrom itertools import chain # Input list initializationlst = [(11, 100), (22, 200), (33, 300), (44, 400), (88, 800)] # using lambdatemp = map(lambda x: str(x), chain.from_iterable(lst)) # Output list initializationOutput = set() # Adding element in Outputfor x in temp: for elem in x: Output.add(elem) # Printing outputprint("Initial List is :", lst)print("Output list is :", Output) |
Initial List is : [(11, 100), (22, 200), (33, 300), (44, 400), (88, 800)]
Output list is : {‘8’, ‘4’, ‘0’, ‘2’, ‘1’, ‘3’}
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


