
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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'])