Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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 | Convert Tuple to integer
Next article icon

Python – Filter Tuples with Integers

Last Updated : 08 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given Tuple list, filter tuples which are having just int data type.

Input : [(4, 5, “GFg”), (3, ), (“Gfg”, )] 
Output : [(3, )] 
Explanation : 1 tuple (3, ) with all integral values. 

Input : [(4, 5, “GFg”), (3, “Best” ), (“Gfg”, )] 
Output : [] 
Explanation : No tuple with all integers.

Method #1 : Using loop + isinstance()

In this, we iterate the each tuple and check for data type other than int, using isinstance(), if found tuple is flagged off and omitted.

Python3




# Python3 code to demonstrate working of
# Filter Tuples with Integers
# Using loop + isinstance()
 
# initializing list
test_list = [(4, 5, "GFg"), (5, 6), (3, ), ("Gfg", )]
 
# printing original list
print("The original list is : " + str(test_list))
 
res_list = []
for sub in test_list:
    res = True
    for ele in sub:
         
        # checking for non-int.
        if not isinstance(ele, int):
            res = False
            break
    if res :
        res_list.append(sub)
         
# printing results
print("Filtered tuples : " + str(res_list))
 
 
Output
The original list is : [(4, 5, 'GFg'), (5, 6), (3, ), ('Gfg', )] Filtered tuples : [(5, 6), (3, )]

Time Complexity: O(n^2), where n is the number of tuples in the list.
Auxiliary Space: O(n), as the filtered list is stored in res_list and its size is proportional to the number of tuples in the list.

Method #2 : Using all() + list comprehension + isinstance()

In this, all() is used to check if all elements are integers using isinstance(), if that checks, tuples are added to result.

Python3




# Python3 code to demonstrate working of
# Filter Tuples with Integers
# Using all() + list comprehension + isinstance()
 
# initializing list
test_list = [(4, 5, "GFg"), (5, 6), (3, ), ("Gfg", )]
 
# printing original list
print("The original list is : " + str(test_list))
 
# list comprehension to encapsulate in 1 liner
res = [sub for sub in test_list if all(isinstance(ele, int) for ele in sub)]
         
# printing results
print("Filtered tuples : " + str(res))
 
 
Output
The original list is : [(4, 5, 'GFg'), (5, 6), (3, ), ('Gfg', )] Filtered tuples : [(5, 6), (3, )]

Time Complexity: O(n*n), where n is the length of the input list. 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”. 

Method 3: Use the filter() function along with lambda function 

Step-by-step approach:

  • Define a lambda function that takes a tuple as input and returns True if all elements of the tuple are integers, else False.
  • Use the filter() function to filter the tuples from the given list of tuples that satisfy the condition specified in the lambda function.
  • Convert the filtered result into a list and store it in a variable.
  • Print the filtered tuples.

Python3




# Python3 code to demonstrate working of
# Filter Tuples with Integers
# Using filter() and lambda function
 
# initializing list
test_list = [(4, 5, "GFg"), (5, 6), (3, ), ("Gfg", )]
 
# printing original list
print("The original list is : " + str(test_list))
 
# lambda function to check if all elements of tuple are integers
is_all_int = lambda tup: all(isinstance(ele, int) for ele in tup)
 
# using filter() to filter tuples with integers
res = list(filter(is_all_int, test_list))
 
# printing results
print("Filtered tuples : " + str(res))
 
 
Output
The original list is : [(4, 5, 'GFg'), (5, 6), (3,), ('Gfg',)] Filtered tuples : [(5, 6), (3,)]

Time complexity: O(n), where n is the number of tuples in the list.
Auxiliary space: O(k), where k is the number of tuples that satisfy the condition specified in the lambda function.

Method 4: Using reduce() 

Step-by-step approach:

  • Import the reduce() function from the functools module.
  • Define a lambda function that takes two arguments, a tuple and a boolean value, and returns True if all elements of the tuple are integers and the boolean value is True, and False otherwise.
  • Use the reduce() function to apply the lambda function to each tuple in the test_list and accumulate the results.
  • Use the filter() function to filter out the tuples that have a True result from the reduce() function.
  • Return the filtered list.

Python3




from functools import reduce
 
# initializing list
test_list = [(4, 5, "GFg"), (5, 6), (3, ), ("Gfg", )]
 
# printing original list
print("The original list is : " + str(test_list))
 
# lambda function to check if all elements of tuple are integers
is_all_int = lambda tup, bool_val: bool_val and all(isinstance(ele, int) for ele in tup)
 
# using reduce() and filter() to filter tuples with integers
res = list(filter(lambda x: reduce(is_all_int, (x, True)), test_list))
 
# printing results
print("Filtered tuples : " + str(res))
 
 
Output
The original list is : [(4, 5, 'GFg'), (5, 6), (3,), ('Gfg',)] Filtered tuples : [(5, 6), (3,)]

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



Next Article
Python | Convert Tuple to integer
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python | Convert Tuple to integer
    Sometimes, while working with records, we can have a problem in which we need to convert the data records to integer by joining them. Let's discuss certain ways in which this task can be performed. Method #1 : Using reduce() + lambda The combination of above functions can be used to perform this tas
    5 min read
  • Python - Flatten Nested Tuples
    Sometimes, while working with Python Tuples, we can have a problem in which we need to perform flattening of tuples, which can be nested and undesired. This can have application across many domains such as Data Science and web development. Let's discuss certain way in which this task can be performe
    7 min read
  • Python - Filter Tuples with All Even Elements
    Given List of tuples, filter only those with all even elements. Input : test_list = [(6, 4, 2, 8), (5, 6, 7, 6), (8, 1, 2), (7, )] Output : [(6, 4, 2, 8)] Explanation : Only 1 tuple with all even elements. Input : test_list = [(6, 4, 2, 9), (5, 6, 7, 6), (8, 1, 2), (7, )] Output : [] Explanation : N
    9 min read
  • Python - Filter Range Length Tuples
    We are given a list of tuples where each tuple contains multiple elements, and our task is to filter out tuples whose lengths do not fall within a specified range. For example, if we have a = [(1, 2), (3, 4, 5), (6,), (7, 8, 9, 10)] and the range (2, 3), we should keep only tuples with 2 or 3 elemen
    3 min read
  • Python - Extract tuples with elements in Range
    Given list of tuples, extract tuples having elements in range. Input : test_list = [(4, 5, 7), (5, 6), (3, 8, 10 ), (4, 10)], strt, end = 5, 6 Output : [(5, 6)] Explanation : Only 1 tuple lies in range of 5-6. Input : test_list = [(4, 5, 7), (5, 6), (3, 8, 10 ), (4, 10)], strt, end = 1, 10 Output :
    4 min read
  • Python - Convert Binary tuple to Integer
    Given Binary Tuple representing binary representation of a number, convert to integer. Input : test_tup = (1, 1, 0) Output : 6 Explanation : 4 + 2 = 6. Input : test_tup = (1, 1, 1) Output : 7 Explanation : 4 + 2 + 1 = 7. Method #1 : Using join() + list comprehension + int() In this, we concatenate t
    5 min read
  • Python - Integers String to Integer List
    In this article, we will check How we can Convert an Integer String to an Integer List Using split() and map()Using split() and map() will allow us to split a string into individual elements and then apply a function to each element. [GFGTABS] Python s = "1 2 3 4 5" # Convert the string to
    2 min read
  • Find Largest Item in a Tuple - Python
    We need to find the largest number or the top N largest numbers from a tuple. For Example: Input: (10,20,23,5,2,90) #tupleOutput: 90Explanation: 90 is the largest element from tuple There are several efficient ways to achieve this: Using max()max() in Python is the most efficient way to find the lar
    4 min read
  • Python - Clearing a tuple
    Sometimes, while working with Records data, we can have a problem in which we may require to perform clearing of data records. Tuples, being immutable cannot be modified and hence makes this job tough. Let's discuss certain ways in which this task can be performed. Method #1 : Using list() + clear()
    4 min read
  • Python - Filter Tuple with Elements capped on K
    Given a List of Tuples, extract tuples in which each element is max K. Input : test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8)], K = 7 Output : [(4, 5, 3), (3, 4, 7), (4, 3, 2)] Explanation : All tuples have maximum value 7. Input : test_list = [(4, 5, 3), (4, 3, 2), (4, 7, 8)], K = 7 Output
    5 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