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
Selected Reading
Program to update list items by their absolute values in Python
Sometimes we need to convert negative numbers in a list to their absolute values while keeping positive numbers unchanged. Python provides several approaches to update list items with their absolute values.
Using map() with Lambda Function
The map() function applies a lambda function to each element in the list ?
def solve(nums):
return list(map(lambda x: abs(x), nums))
nums = [5, -7, -6, 4, 6, -9, 3, -6, -2]
result = solve(nums)
print("Original list:", nums)
print("Absolute values:", result)
Original list: [5, -7, -6, 4, 6, -9, 3, -6, -2] Absolute values: [5, 7, 6, 4, 6, 9, 3, 6, 2]
Using List Comprehension
List comprehension provides a more Pythonic and readable approach ?
nums = [5, -7, -6, 4, 6, -9, 3, -6, -2]
result = [abs(x) for x in nums]
print("Original list:", nums)
print("Absolute values:", result)
Original list: [5, -7, -6, 4, 6, -9, 3, -6, -2] Absolute values: [5, 7, 6, 4, 6, 9, 3, 6, 2]
In-Place Update Using enumerate()
To modify the original list without creating a new one, use enumerate() ?
nums = [5, -7, -6, 4, 6, -9, 3, -6, -2]
print("Before update:", nums)
for i, value in enumerate(nums):
nums[i] = abs(value)
print("After update:", nums)
Before update: [5, -7, -6, 4, 6, -9, 3, -6, -2] After update: [5, 7, 6, 4, 6, 9, 3, 6, 2]
Comparison
| Method | Creates New List? | Readability | Best For |
|---|---|---|---|
map() |
Yes | Moderate | Functional programming style |
| List comprehension | Yes | High | Most Pythonic approach |
enumerate() |
No | High | Memory-efficient in-place updates |
Conclusion
Use list comprehension for the most readable and Pythonic solution. Choose enumerate() for in-place updates when memory efficiency is important. The map() approach works well in functional programming contexts.
Advertisements
