Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Extract digits from Tuple list
Next article icon

Python - Extract digits from Tuple list

Last Updated : 21 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while working with Python lists, we can have a problem in which we need to perform extraction of all the digits from tuple list. This kind of problem can find its application in data domains and day-day programming. Let's discuss certain ways in which this task can be performed.

Input : test_list = [(15, 3), (3, 9)] 
Output : [9, 5, 3, 1]

Input : test_list = [(15, 3)] 
Output : [5, 3, 1] 

Method #1: Using map() + chain.from_iterable() + set() + loop 
The combination of above functions can be used to solve this problem. In this, we perform the task of flattening list using chain.from_iterable(), and then the digits are extracted using brute method. set() is used to remove duplicate digits.

Python3
# Python3 code to demonstrate working of  # Extract digits from Tuple list # Using map() + chain.from_iterable() + set() + loop from itertools import chain  # initializing list test_list = [(15, 3), (3, 9), (1, 10), (99, 2)]  # printing original list print("The original list is : " + str(test_list))  # Extract digits from Tuple list # Using map() + chain.from_iterable() + set() + loop temp = map(lambda ele: str(ele), chain.from_iterable(test_list)) res = set() for sub in temp:     for ele in sub:         res.add(ele)  # printing result  print("The extracted digits : " + str(res))  

Output
The original list is : [(15, 3), (3, 9), (1, 10), (99, 2)] The extracted digits : {'1', '0', '3', '2', '9', '5'}

Time Complexity: O(n*m), where n is the length of the input list and m is the maximum length of any tuple element in the list.
Auxiliary Space: O(k), where k is the number of unique digits in the input list. This is because the set data structure is used to store the extracted digits.

Method #2: Using regex expression 
This is yet another way in which this task can be performed. In this, an appropriate regex expression is used to extract the required unique digits.

Python3
# Python3 code to demonstrate working of  # Extract digits from Tuple list # Using regex expression import re  # initializing list test_list = [(15, 3), (3, 9), (1, 10), (99, 2)]  # printing original list print("The original list is : " + str(test_list))  # Extract digits from Tuple list # Using regex expression temp = re.sub(r'[\[\]\(\), ]', '', str(test_list)) res = [int(ele) for ele in set(temp)]  # printing result  print("The extracted digits : " + str(res))  

Output
The original list is : [(15, 3), (3, 9), (1, 10), (99, 2)] The extracted digits : [5, 9, 2, 0, 1, 3]

Time complexity: O(n), where n is the length of the input list. 
Auxiliary space: O(n), where n is the length of the input list.

Method #3: Using list(),str(),map(),set() methods .

Initially converted all elements of tuple to string and concatenated them.Later used set() method to remove the duplicates, converted string elements to integer elements and finally converted them to list datatype.

Python3
# Python3 code to demonstrate working of # Extract digits from Tuple list  # initializing list test_list = [(15, 3), (3, 9), (1, 10), (99, 2)]  # printing original list print("The original list is : " + str(test_list)) x="" # Extract digits from Tuple list for i in test_list:     for j in i:         x+=str(j) res=list(map(int,set(x))) # printing result print("The extracted digits : " + str(res)) 

Output
The original list is : [(15, 3), (3, 9), (1, 10), (99, 2)] The extracted digits : [2, 3, 0, 1, 9, 5]

Method#4: Using list Comprehension

Python3
# Initializing list test_list = [(15, 3), (3, 9), (1, 10), (99, 2)]  # Printing original list print("The original list is : " + str(test_list))  # Extracting digits from Tuple list using list comprehensions temp = ''.join([str(i) for sublist in test_list for i in sublist]) result = set(temp) result = [int(i) for i in result] # Printing result print("The extracted digits : " + str(list(result))) #This code is contributed by Vinay Pinjala. 

Output
The original list is : [(15, 3), (3, 9), (1, 10), (99, 2)] The extracted digits : ['0', '9', '1', '3', '5', '2']

Time complexity : O(n)
Auxiliary Space : O(n)

METHOD 5:Using reduce and set

APPROACH:

This program extracts digits from a tuple list using the reduce function from the functools module.

ALGORITHM:

1.Define the tuple list.
2.Use the reduce function to concatenate all the elements of the tuple into a single string.
3.Convert each string into a set to remove duplicates.
4.Merge all sets into a single set.
5.Convert the set of strings into a set of individual digits.
6.Print the original list and the extracted digits.

Python3
from functools import reduce  tup_list = [(15, 3), (3, 9), (1, 10), (99, 2)]  digit_list = set(reduce(lambda a,b: str(a) + str(b), tup) for tup in tup_list) digit_list = set(digit for string in digit_list for digit in string)  print("The original list is:", tup_list) print("The extracted digits:", digit_list) 

Output
The original list is: [(15, 3), (3, 9), (1, 10), (99, 2)] The extracted digits: {'9', '3', '1', '5', '2', '0'}

Time Complexity: O(nlogn) (where n is the number of tuples in the list)
Space Complexity: O(n) (where n is the number of digits extracted)

METHOD 6: Using heapq:

Algorithm:

  1. Initialize a list 'test_list' with tuples of integers.
  2. Print the original list 'test_list'.
  3. Using a list comprehension, extract all the digits from the tuples and join them as a single string.
  4. Convert the string to a set to extract only unique digits.
  5. Convert the set back to a list and sort the list.
  6. Print the resulting list of unique digits.
Python3
import heapq  # Initializing list test_list = [(15, 3), (3, 9), (1, 10), (99, 2)]  # Printing original list print("The original list is : " + str(test_list))  # Extracting digits from Tuple list using heapq result = [] for tpl in test_list:     result.extend(list(tpl))  # Converting the result list to heap heapq.heapify(result)  # Extracting unique digits from heap unique_digits = set() while result:     digits = str(heapq.heappop(result))     for digit in digits:         unique_digits.add(int(digit))  # Printing result print("The extracted digits : " + str(list(unique_digits))) #This code is contributed by Rayudu. 

Output
The original list is : [(15, 3), (3, 9), (1, 10), (99, 2)] The extracted digits : [0, 1, 2, 3, 5, 9] 

Time Complexity:

Initializing the list takes O(1) time.
Printing the list takes O(n) time, where n is the number of tuples in the list.
Using a list comprehension to extract digits takes O(nk) time, where k is the average number of digits in each tuple.
Converting the string to a set takes O(k) time, where k is the total number of digits.
Converting the set back to a list and sorting takes O(k log k) time.
Printing the resulting list takes O(k) time.
Therefore, the overall time complexity of the code is O(nk + k log k).

Space Complexity:

Initializing the list takes O(n) space, where n is the number of tuples in the list.
Extracting digits using list comprehension creates a new list which takes O(nk) space.
Converting the string to a set takes O(k) space.
Converting the set back to a list takes O(k) space.
Therefore, the overall space complexity of the code is O(nk + 2k) or simply O(nk).


Next Article
Python - Extract digits from Tuple list

M

manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python tuple-programs
  • Python List-of-Tuples
Practice Tags :
  • python

Similar Reads

    Python - Extract digits from given string
    We need to extract the digit from the given string. For example we are given a string s=""abc123def456gh789" we need to extract all the numbers from the string so the output for the given string will become "123456789" In this article we will show different ways to extract digits from a string in Py
    2 min read
    Python - Extract Rear K digits from Numbers
    Given an Integer list, extract rear K digits from it. Input : test_list = [5645, 23567, 34543, 87652, 2342], K = 2 Output : [45, 67, 43, 52, 42] Explanation : Last 2 digits extracted. Input : test_list = [5645, 23567, 34543, 87652, 2342], K = 4 Output : [5645, 3567, 4543, 7652, 2342] Explanation : L
    5 min read
    Extract Elements from a Python List
    When working with lists in Python, we often need to extract specific elements. The easiest way to extract an element from a list is by using its index. Python uses zero-based indexing, meaning the first element is at index 0. Pythonx = [10, 20, 30, 40, 50] # Extracts the last element a = x[0] print(
    2 min read
    Python - Extract tuples having K digit elements
    Given a list of tuples, extract all tuples having K digit elements. Input : test_list = [(54, 2), (34, 55), (222, 23), (12, 45), (78, )], K = 2 Output : [(34, 55), (12, 45), (78,)] Explanation : All tuples have numbers with 2 digits. Input : test_list = [(54, 2), (34, 55), (222, 23), (12, 45), (782,
    6 min read
    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 l
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences