Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Change the signs of elements of tuples in a list
When it is required to change the signs of elements in a list of tuples, you can use iteration along with the abs() method to manipulate positive and negative values. This technique is useful for standardizing tuple formats or data preprocessing.
Example
Below is a demonstration of changing tuple elements to have positive first elements and negative second elements ?
my_list = [(51, -11), (-24, -24), (11, 42), (-12, 45), (-45, 26), (-97, -4)]
print("The list is :")
print(my_list)
my_result = []
for sub in my_list:
my_result.append((abs(sub[0]), -abs(sub[1])))
print("The result is :")
print(my_result)
The list is : [(51, -11), (-24, -24), (11, 42), (-12, 45), (-45, 26), (-97, -4)] The result is : [(51, -11), (24, -24), (11, -42), (12, -45), (45, -26), (97, -4)]
Using List Comprehension
A more concise approach uses list comprehension for the same result ?
my_list = [(51, -11), (-24, -24), (11, 42), (-12, 45), (-45, 26), (-97, -4)]
print("Original list:")
print(my_list)
# Using list comprehension
my_result = [(abs(x), -abs(y)) for x, y in my_list]
print("Modified list:")
print(my_result)
Original list: [(51, -11), (-24, -24), (11, 42), (-12, 45), (-45, 26), (-97, -4)] Modified list: [(51, -11), (24, -24), (11, -42), (12, -45), (45, -26), (97, -4)]
How It Works
abs(sub[0])? Converts the first element to positive by taking its absolute value-abs(sub[1])? Converts the second element to negative by taking absolute value and negating itThe tuple unpacking
(x, y)in list comprehension makes the code more readable
Different Sign Patterns
You can modify the pattern to achieve different sign combinations ?
my_list = [(51, -11), (-24, 24), (11, -42)]
# Both positive
both_positive = [(abs(x), abs(y)) for x, y in my_list]
print("Both positive:", both_positive)
# Both negative
both_negative = [(-abs(x), -abs(y)) for x, y in my_list]
print("Both negative:", both_negative)
# First negative, second positive
first_neg_second_pos = [(-abs(x), abs(y)) for x, y in my_list]
print("First negative, second positive:", first_neg_second_pos)
Both positive: [(51, 11), (24, 24), (11, 42)] Both negative: [(-51, -11), (-24, -24), (-11, -42)] First negative, second positive: [(-51, 11), (-24, 24), (-11, 42)]
Conclusion
Use abs() with appropriate negation to standardize tuple element signs. List comprehension provides a cleaner solution than traditional loops for this type of transformation.
