
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Python - Change the signs of elements of tuples in a list
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.
- Related Questions & Answers
- Python program to find Tuples with positive elements in a List of tuples
- Python program to find Tuples with positive elements in List of tuples
- Combining tuples in list of tuples in Python
- Find top K frequent elements from a list of tuples in Python
- Python program to convert elements in a list of Tuples to Float
- Python program to Convert a elements in a list of Tuples to Float
- Count tuples occurrence in list of tuples in Python
- Convert list of tuples to list of list in Python
- Find the tuples containing the given element from a list of tuples in Python
- Remove duplicate tuples from list of tuples in Python
- Convert list of tuples into list in Python
- Update a list of tuples using another list in Python
- Convert list of strings to list of tuples in Python
- Convert list of tuples to list of strings in Python
- Summation of tuples in list in Python
Advertisements