Python Extract digits from Tuple list (original) (raw)
Last Updated : 7 Nov, 2025
Given a list of tuples containing numbers of varying lengths, the task is to extract all unique digits present in those tuples.
**Examples:
**Input: list = [(15, 3), (3, 9)]
**Output: [9, 5, 3, 1]**Input: list = [(15, 3)]
**Output: [5, 3, 1]
Using List Comprehension + Set
Python `
t = [(15, 3), (3, 9), (1, 10), (99, 2)]
temp = ''.join([str(i) for s1 in t for i in s1]) res = [int(i) for i in set(temp)] print(res)
`
**Explanation:
- **[str(i) for s1 in t for i in s1]: Converts each number in all tuples to a string.
- ' ****'.join(...):** Joins all string numbers into one continuous string.
- **set(temp): Removes duplicate digits.
- **[int(i) for i in set(temp)]: Converts unique string digits back to integers. Python `
from itertools import chain
t = [(15, 3), (3, 9), (1, 10), (99, 2)] s = map(str, chain.from_iterable(t)) res = {d for n in s for d in n} print(res)
`
Output
{'0', '2', '9', '5', '3', '1'}
**Explanation:
- **chain.from_iterable(t): Flattens all tuples into a single sequence.
- **map(str, ...): Converts each number to a string.
- ****{d for n in s for d in n}:** Extracts individual digits and keeps only unique ones.
Using Regex
A compact method that converts the tuple list to a string, removes unwanted characters using regex, and extracts unique digits using set().
Python `
import re
t = [(15, 3), (3, 9), (1, 10), (99, 2)] s = re.sub(r'[[](), ]', '', str(t)) res = [int(i) for i in set(s)] print(res)
`
**Explanation:
- **str(t): Converts tuple list to string.
- **re.sub(r'[\[\]\(\), ]', '', str(t)): Removes brackets, commas, and spaces.
- **set(s): Collects unique digit characters.
- **int(i) for i in set(s): Converts them back to integers.
Using Nested Loops + set()
A simple approach that iterates through each tuple, collects all digits as strings, and uses set() to extract unique digits.
Python `
t = [(15, 3), (3, 9), (1, 10), (99, 2)]
s = '' for x in t: for y in x: s += str(y) res = list(map(int, set(s))) print(res)
`