Q:

Python program to perform AND operation on tuples

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

AND Operation on Tuples

In this program, we are given two tuples. We need to create a python program to return a tuple that contains the AND elements.

Input:
tuple1 = (4, 1, 7, 9, 3), 
tuple2 = (2, 4, 6, 7, 8)

Output:
(0, 0, 6, 1, 0)

Python provides multiple ways to solve the problem and here we will see some of them working.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method to solve the problem is by simply computing the AND operation of all elements of tuples using the AND operator in the lambda function and mapping them. This collection is then converted to a tuple using the tuple() method.

# Python program to perform AND operation on tuples 

# initializing and printing tuples
tuple1 = (4, 1, 7, 9, 3)
tuple2 = (2, 4, 6, 7, 8)
print("The elements of first tuple are "+str(tuple1))
print("The elements of second tuple are  "+str(tuple2))
  
# Performing AND operation on tuples
andOperationTuple = tuple(map(lambda val1, val2: val1 & val2, tuple1, tuple2))
  
# Printing result
print("The result of AND operation on tuples are "+str(andOperationTuple))

Output:

The elements of first tuple are (4, 1, 7, 9, 3)
The elements of second tuple are  (2, 4, 6, 7, 8)
The result of AND operation on tuples are (0, 0, 6, 1, 0)

Method 2:

Another method to solve the problem is by using the map() method to map each element of both tuples. And the operation on mapping is done using the iand() method to perform AND operation.

# Python program to perform AND operation on tuples 

import operator

# Initializing and printing tuples
tuple1 = (4, 1, 7, 9, 3)
tuple2 = (2, 4, 6, 7, 8)
print("The elements of first tuple are "+str(tuple1))
print("The elements of second tuple are  "+str(tuple2))
  
# Performing AND operation on tuples
andOperationTuple = tuple(map(operator.iand, tuple1, tuple2))
  
# Printing result
print("The result of AND operation on tuples are "+str(andOperationTuple))

Output:

The elements of first tuple are (4, 1, 7, 9, 3)
The elements of second tuple are  (2, 4, 6, 7, 8)
The result of AND operation on tuples are (0, 0, 6, 1, 0)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to find the maximum nested tuple... >>
<< Python program to check if the given tuple is a tr...