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

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.
Submitted by Shivang Yadav, on July 02, 2021

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.

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

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:

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

Preparation

What's New

Top Interview Coding Problems/Challenges!