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
Python – Append given number with every element of the list
When you need to add a specific number to every element in a list, Python offers several approaches. The most common method uses list comprehension, which provides a concise and readable solution.
Using List Comprehension
List comprehension allows you to create a new list by applying an operation to each element ?
numbers = [25, 36, 75, 36, 17, 7, 8, 0]
print("Original list:")
print(numbers)
append_value = 6
result = [x + append_value for x in numbers]
print("List after appending", append_value, "to each element:")
print(result)
Original list: [25, 36, 75, 36, 17, 7, 8, 0] List after appending 6 to each element: [31, 42, 81, 42, 23, 13, 14, 6]
Using map() Function
The map() function applies a function to every element in the list ?
numbers = [10, 20, 30, 40]
append_value = 5
result = list(map(lambda x: x + append_value, numbers))
print("Original list:", numbers)
print("Modified list:", result)
Original list: [10, 20, 30, 40] Modified list: [15, 25, 35, 45]
Using for Loop
A traditional approach using a for loop to iterate and modify each element ?
numbers = [1, 2, 3, 4, 5]
append_value = 10
result = []
for num in numbers:
result.append(num + append_value)
print("Original list:", numbers)
print("Modified list:", result)
Original list: [1, 2, 3, 4, 5] Modified list: [11, 12, 13, 14, 15]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| List Comprehension | High | Fast | Simple operations |
| map() with lambda | Medium | Fast | Functional programming |
| for Loop | High | Slower | Complex operations |
Conclusion
List comprehension is the most Pythonic way to append a number to every element in a list. Use map() for functional programming approaches or for loops when you need more complex logic.
Advertisements
