# Convert list of tuples into digits in Python

PythonServer Side ProgrammingProgramming

Python has a wide variety of data manipulation capabilities. We have a scenario in which we are given a list which has elements which are pair of numbers as tuples. In this article we will see how to extract the unique digits from the elements of a list which are tuples.

## With re and set

We can use regular expression module and its function called sub. It is used to replace a string that matches a regular expression instead of perfect match. So we design a regular expression to convert the tuples into normal strings and then apply the set function to get the unique digits.

## Example

Live Demo

import re
listA = [(21, 3), (13, 4), (15, 7),(8,11)]
# Given list
print("Given list : \n", listA)
temp = re.sub(r'[, ]', '', str(listA))
# Using set
res = [int(i) for i in set(temp)]
# Result
print("List of digits: \n",res)

## Output

Running the above code gives us the following result −

Given list :
[(21, 3), (13, 4), (15, 7), (8, 11)]
List of digits:
[1, 3, 2, 5, 4, 7, 8])

## With chain and set

The itertools module provides chain method which we can use to get the elements from the list. Then create an empty set and keep adding the elements to that set one by one.

## Example

Live Demo

from itertools import chain
listA = [(21, 3), (13, 4), (15, 7),(8,11)]
# Given list
print("Given list : \n", listA)
temp = map(lambda x: str(x), chain.from_iterable(listA))
res = set()
for i in temp:
for elem in i:
# Result
print("set of digits: \n",res)

## Output

Running the above code gives us the following result −

Given list :
[(21, 3), (13, 4), (15, 7), (8, 11)]
set of digits:
['1', '3', '2', '5', '4', '7', '8'])
Updated on 20-May-2020 11:02:52