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)]
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:
Output:
Method 2:
The code we used in method 1 can be converted to a single line of code using list comprehension in Python.
Program:
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer