Q:

Python | Elementwise AND in Tuples

belongs to collection: Python Tuple Programs

0

Example:

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

Elementwise AND operation in Tuple

We will seek each element of both tuples and perform AND operations on the same index. And return all the resultant values of the AND operation.

Input:
tup1 = (3, 1, 4), tup2 = (5, 2, 6)

Output:
(1, 0, 4)

All Answers

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

Method 1:

One method to perform AND operation on each element of the tuple is by using generator expression for performing the AND operation and zipping together both the tuples using the zip() method.

# Program to perform elementwise AND operation 
# on Tuples using generator expression

# initializing and printing tuples 
tup1 = (3, 1, 4) 
tup2 = (5, 2, 6) 
print("All elements of Tuple 1 are " + str(tup1)) 
print("All elements of Tuple 2 are " + str(tup2)) 
  
# Performing AND operation on each element of the tuple,
andTup = tuple(val1 & val2 for val1, val2 in zip(tup1, tup2)) 
  
# printing result 
print("The tuple formed after elementwise AND operation are " + str(andTup)) 

Output:

All elements of Tuple 1 are (3, 1, 4)
All elements of Tuple 2 are (5, 2, 6)
The tuple formed after elementwise AND operation are (1, 0, 4)

Method 2:

Another approach that can solve the problem is by using "iand" to perform an extended logic of the AND operation and map it using map() and then convert the map to a tuple using the tuple() method.

# Program to perform elementwise AND operation 
# on Tuples using generator expression

# Importing iand operator 
from operator import iand 

# initializing and printing tuples 
tup1 = (3, 1, 4) 
tup2 = (5, 2, 6) 
print("All elements of Tuple 1 are " + str(tup1)) 
print("All elements of Tuple 2 are " + str(tup2)) 
  
# Performing AND operation on each element of the tuple,
andTup = tuple(map(iand, tup1, tup2))  
  
# printing result 
print("The tuple formed after elementwise AND operation are " + str(andTup)) 

Output:

All elements of Tuple 1 are (3, 1, 4)
All elements of Tuple 2 are (5, 2, 6)
The tuple formed after elementwise AND operation are (1, 0, 4)

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 check if the given tuple is a tr... >>
<< Python | Records with Value at K index...