Q:

Python program to change the sign of elements of tuples in a list

belongs to collection: Python Tuple Programs

0

Example:

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

List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of ordered set of values enclosed in square brackets [].

Example:

list = [3 ,1,  5, 7]

A list of tuples is a list whose each element is a tuple.

Example:

upList = [("python", 7), ("learn" , 1), ("programming", 7), ("code" , 3)]

Changing The Sign of Elements of Tuples in a list

We need to convert the Ist 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)]

All Answers

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

Method 1:

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:

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)]

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 convert integer values in a list... >>
<< Python program to flatten tuple of lists to a tupl...