
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Change Signs of Elements in Tuples of a List in Python
When it is required to change the signs of the elements in a list of tuple, a simple iteration, the ‘abs’ method and the ‘append’ method can be used.
Example
Below is a demonstration of the same
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)
Output
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)]
Explanation
A list of tuple is defined and is displayed on the console.
An empty list is defined.
The original list is iterated over.
The ‘abs’ method is used to get the absolute value of the negative elements of the list.
This result is appended to the empty list.
This is displayed as output on the console.
Advertisements