Q:

Python | Tuple elements inversions

belongs to collection: Python Tuple Programs

0

Example:

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

Performing the Tuple element inversion

We are given a tuple consisting of integer values only. And we will create a program to perform tuple element inversion.

Input:
(3, 1, 5, 9)

Output:
(-4, -2, -6, -10)

To solve the problem, we will be traversing each element of the tuple. And perform bitwise inversion operation on them and return the inverted element tuple.

In the Python programming language, we have multiple methods to perform tuple inversion.

All Answers

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

Method 1:

One method to invert elements of the tuple is by using a lambda function inside the map() with the function as an inversion operator. This will create a collection will all elements of the tuple inverted. Then we will convert it into a tuple.

# Python program to perform 
# tuple elements inversion

# Creating and print the 
# initial tuple
myTuple = (3, 1, 5, 9)
print("Initially elements of the tuple are " + str(myTuple))

# Bitwise inverting elements 
# of the tuple
invTuple = tuple(list(map(lambda x: ~x, list(myTuple))))

print("Bitwise inversion of all tuple elements are " + str(invTuple))

Output:

Initially elements of the tuple are (3, 1, 5, 9)
Bitwise inversion of all tuple elements are (-4, -2, -6, -10)

Method 2:

Another method to bitwise inverts the elements of the tuple is by using the operator.invert instead of inversion operator as the map's lambda function.

# Python program to perform 
# tuple elements inversion

import operator

# Creating and print the initial tuple
myTuple = (3, 1, 5, 9)
print("Initially elements of the tuple are " + str(myTuple))

# Bitwise inverting elements of the tuple
invTuple = tuple(list(map(operator.invert, list(myTuple))))

print("Bitwise inversion of all tuple elements are " + str(invTuple))

Output:

Initially elements of the tuple are (3, 1, 5, 9)
Bitwise inversion of all tuple elements are (-4, -2, -6, -10)

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 | Union of Tuples... >>
<< Python | Zip Uneven Tuple...