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 - Sum of tuple elements
Next article icon

Python - AND operation between Tuples

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

Sometimes, while working with records, we might have a common problem of performing AND operation contents of one tuple with corresponding index of other tuple. This has application in almost all the domains in which we work with tuple records especially Data Science. Let’s discuss certain ways in which this task can be performed. 

Method #1 : Using map() + lambda Combination of above functionalities can solve the problem for us. In this, we compute the AND using lambda functions and extend the logic to keys using map(). 

Python3
# Python3 code to demonstrate working of # Cross Tuple AND operation # using map() + lambda  # initialize tuples  test_tup1 = (10, 4, 5) test_tup2 = (2, 5, 18)  # printing original tuples  print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2))  # Cross Tuple AND operation # using map() + lambda res = tuple(map(lambda i, j: i & j, test_tup1, test_tup2))  # printing result print("Resultant tuple after AND operation : " + str(res)) 
Output : 
The original tuple 1 : (10, 4, 5) The original tuple 2 : (2, 5, 18) Resultant tuple after AND operation : (2, 4, 0)

Method #2 : Using map() + iand() The combination of above functions can help us achieve this task. In this, we first extend the logic to all using map() and then perform AND of each index using iand(). 

Python3
# Python3 code to demonstrate working of # Cross Tuple AND operation # using map() + iand() import operator  # initialize tuples  test_tup1 = (10, 4, 5) test_tup2 = (2, 5, 18)  # printing original tuples  print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2))  # Cross Tuple AND operation # using map() + iand() res = tuple(map(operator.iand, test_tup1, test_tup2))  # printing result print("Resultant tuple after AND operation : " + str(res)) 
Output : 
The original tuple 1 : (10, 4, 5) The original tuple 2 : (2, 5, 18) Resultant tuple after AND operation : (2, 4, 0)

Method #3: Using List comprehension

This approach is similar to the previous ones but uses a more concise and readable syntax using list comprehension.

Python3
# Python3 code to demonstrate working of # Cross Tuple AND operation # using List comprehension  # initialize tuples  test_tup1 = (10, 4, 5) test_tup2 = (2, 5, 18)    # printing original tuples  print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2))    # Cross Tuple AND operation # using List comprehension res = tuple([i & j for i,j in zip(test_tup1, test_tup2)])    # printing result print("Resultant tuple after AND operation : " + str(res)) #This code is contributed by Edula Vinay Kumar Reddy 

Output
The original tuple 1 : (10, 4, 5) The original tuple 2 : (2, 5, 18) Resultant tuple after AND operation : (2, 4, 0)

Time complexity: O(n) where n is the length of the tuples
Auxiliary Space: O(n) as we are creating a new tuple of the same size as the input tuples

Method #4: Using zip():

Python3
test_tup1 = (10, 4, 5) test_tup2 = (2, 5, 18) # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) res = tuple([i & j for i, j in zip(test_tup1, test_tup2)]) print(res) #This code is contributed by Jyothi pinjala 

Output
The original tuple 1 : (10, 4, 5) The original tuple 2 : (2, 5, 18) (2, 4, 0)

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

Method #5: Using a for loop

Step-by-step approach:

  • Initialize an empty list called result.
  • Iterate over the indices of the input tuples using the range() function.
  • Compute the bitwise AND of the corresponding elements of the input tuples using the & operator.
  • Append the result to the result list.
  • Convert the result list to a tuple using the tuple() function.
  • Return the tuple.
Python3
def bitwise_and_tuples(tup1, tup2):     result = []     for i in range(len(tup1)):         result.append(tup1[i] & tup2[i])     return tuple(result) test_tup1 = (10, 4, 5) test_tup2 = (2, 5, 18) res = bitwise_and_tuples(test_tup1, test_tup2) print(res) 

Output
(2, 4, 0)

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


Next Article
Python - Sum of tuple elements
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python tuple-programs
Practice Tags :
  • python

Similar Reads

  • Python Tuples
    A tuple in Python is an immutable ordered collection of elements. Tuples are similar to lists, but unlike lists, they cannot be changed after their creation (i.e., they are immutable). Tuples can hold elements of different data types. The main characteristics of tuples are being ordered , heterogene
    7 min read
  • Tuple Operations in Python
    Python Tuple is a collection of objects separated by commas. A tuple is similar to a Python list in terms of indexing, nested objects, and repetition but the main difference between both is Python tuple is immutable, unlike the Python list which is mutable. [GFGTABS] Python # Note : In case of list,
    7 min read
  • Create a List of Tuples in Python
    The task of creating a list of tuples in Python involves combining or transforming multiple data elements into a sequence of tuples within a list. Tuples are immutable, making them useful when storing fixed pairs or groups of values, while lists offer flexibility for dynamic collections. For example
    3 min read
  • Create a tuple from string and list - Python
    The task of creating a tuple from a string and a list in Python involves combining elements from both data types into a single tuple. The list elements are added as individual items and the string is treated as a single element within the tuple. For example, given a = ["gfg", "is"] and b = "best", t
    3 min read
  • Access front and rear element of Python tuple
    Sometimes, while working with records, we can have a problem in which we need to access the initial and last data of a particular record. This kind of problem can have application in many domains. Let's discuss some ways in which this problem can be solved. Method #1: Using Access Brackets We can pe
    6 min read
  • Python - Element Index in Range Tuples
    Sometimes, while working with Python data, we can have a problem in which we need to find the element position in continuous equi ranged tuples in list. This problem has applications in many domains including day-day programming and competitive programming. Let's discuss certain ways in which this t
    6 min read
  • Unpacking a Tuple in Python
    Tuple unpacking is a powerful feature in Python that allows you to assign the values of a tuple to multiple variables in a single line. This technique makes your code more readable and efficient. In other words, It is a process where we extract values from a tuple and assign them to variables in a s
    2 min read
  • Unpacking Nested Tuples-Python
    The task of unpacking nested tuples in Python involves iterating through a list of tuples, extracting values from both the outer and inner tuples and restructuring them into a flattened format. For example, a = [(4, (5, 'Gfg')), (7, (8, 6))] becomes [(4, 5, 'Gfg'), (7, 8, 6)]. Using list comprehensi
    3 min read
  • Python | Slice String from Tuple ranges
    Sometimes, while working with data, we can have a problem in which we need to perform the removal from strings depending on specified substring ranges. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + list slicing: This is the brute force task to perform this t
    3 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
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