- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to update list items by their absolute values in Python
Suppose we have a list of numbers called nums with positive and negative numbers. We have to update this list so that the final list will only hold the absolute value of each element.
So, if the input is like nums = [5,-7,-6,4,6,-9,3,-6,-2], then the output will be [5, 7, 6, 4, 6, 9, 3, 6, 2]
To solve this, we will follow these steps −
- Solve this by map and list operations
- define one anonymous function say l, that takes x as argument and returns abs(x)
- using map() method convert each element e from nums to l(e)
- return the list
Example
Let us see the following implementation to get better understanding −
def solve(nums): return list(map(lambda x:abs(x), nums)) nums = [5,-7,-6,4,6,-9,3,-6,-2] print(solve(nums))
Input
[5,-7,-6,4,6,-9,3,-6,-2]
Output
[5, 7, 6, 4, 6, 9, 3, 6, 2]
Advertisements