Home »
Python »
Python Programs
Python program to change the sign of elements of tuples in a list
Learn: How to change the sign of elements of tuples in a list in Python?
By Shivang Yadav Last updated : December 15, 2023
Problem statement
Here, we have a list of tuples and we need to change the sign of the element of the tuple, convert all first elements of the tuple to positive sign and second elements of the tuple of negative sign.
We need to convert the list values of tuples to positive and IInd values of tuples to negative.
Example
Input:
[(-1, 4), (3, 1), (7, -6), (-4, 7)]
Output:
[(1, -4), (3, -1), (7, -6), (4, -7)]
Prerequisites
To understand the solution, you must know the following Python topics:
Changing The Sign of Elements of Tuples in a list
To perform the conversion of signs of the tuple elements. We will simply make all the values at index 1 to positive and all values at index 2 to negative. And then return the converted tuple list. To perform this task in Python, we have multiple methods. Let's see them,
Method 1: Using the sign conversion
One method to perform the sign conversion is by simply traversing the list using a loop and then for each tuple converting the sign of elements using the abs() function that returns the absolute value of the passed value. For negative, we will make the absolute value negative by multiplying it by (-1).
Program
# Python program to change sign of element in a list
tupList = [(-1, 4), (3, 1), (7, -6), (-4, -7)]
print("Initial tuple list : " + str(tupList))
signedTupList = []
for vals in tupList:
signedTupList.append((abs(vals[0]), -1*abs(vals[1])))
print("Updated Tuple list : " + str(signedTupList))
Output:
Initial tuple list : [(-1, 4), (3, 1), (7, -6), (-4, -7)]
Updated Tuple list : [(1, -4), (3, -1), (7, -6), (4, -7)]
Method 2: Using list comprehension
The code we used in method 1 can be converted to a single line of code using list comprehension in Python.
Program
# Python program to change sign of element in a list
tupList = [(-1, 4), (3, 1), (7, -6), (-4, -7)]
print("Initial tuple list : " + str(tupList))
signedTupList = [(abs(val[0]), -1*abs(val[1])) for val in tupList]
print("Updated Tuple list : " + str(signedTupList))
Output:
Initial tuple list : [(-1, 4), (3, 1), (7, -6), (-4, -7)]
Updated Tuple list : [(1, -4), (3, -1), (7, -6), (4, -7)]
Python Tuple Programs »