
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Convert list of tuples into digits in Python
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
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
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)) # Using set and add res = set() for i in temp: for elem in i: res.add(elem) # 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'])
- Related Articles
- Convert list of tuples into list in Python
- Python program to convert a list of tuples into Dictionary
- Convert list of tuples to list of list in Python
- Convert list of strings to list of tuples in Python
- Convert list of tuples to list of strings in Python
- Convert dictionary to list of tuples in Python
- Convert list into list of lists in Python
- Combining tuples in list of tuples in Python
- Convert a string representation of list into list in Python
- Count tuples occurrence in list of tuples in Python
- Python program to convert elements in a list of Tuples to Float
- Convert list of string into sorted list of integer in Python
- Python - Convert given list into nested list
- Remove duplicate tuples from list of tuples in Python
- Convert set into a list in Python
