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
Adding value to sublists in Python
Sometimes we need to add new values to sublists in an existing list. In this article, we will see how new values can be inserted into sublists by combining them with each item of the existing list.
Using List Comprehension with Fixed-Length Sublists
When you have sublists of the same length, you can use list comprehension to unpack and add new values ?
data = [[10, 20], [14, 8], ['Mon', 'Tue']]
print("Given List:")
print(data)
s = "Rise"
t = "fast"
result = [[m, n, s, t] for m, n in data]
print("\nNew List:")
print(result)
Given List: [[10, 20], [14, 8], ['Mon', 'Tue']] New List: [[10, 20, 'Rise', 'fast'], [14, 8, 'Rise', 'fast'], ['Mon', 'Tue', 'Rise', 'fast']]
Using + Operator for Variable-Length Sublists
The + operator can add new elements to sublists of varying lengths. You can even add another list as a nested element ?
data = [[1.5, 2.5, 'Tue'], [0.8, 0.9, 'Ocean'], [6.8, 4.3], [9]]
print("Given List:")
print(data)
# Add a list as a single element
new_element = ["Rise", "Fast"]
result = [sub + [new_element] for sub in data]
print("\nNew List:")
print(result)
Given List: [[1.5, 2.5, 'Tue'], [0.8, 0.9, 'Ocean'], [6.8, 4.3], [9]] New List: [[1.5, 2.5, 'Tue', ['Rise', 'Fast']], [0.8, 0.9, 'Ocean', ['Rise', 'Fast']], [6.8, 4.3, ['Rise', 'Fast']], [9, ['Rise', 'Fast']]]
Adding Individual Elements Instead of Nested Lists
To add individual elements rather than nested lists, use the + operator with the new values directly ?
data = [[1, 2], [3, 4], [5]]
print("Original List:")
print(data)
# Add individual elements
new_values = ["A", "B"]
result = [sub + new_values for sub in data]
print("\nAfter adding individual elements:")
print(result)
Original List: [[1, 2], [3, 4], [5]] After adding individual elements: [[1, 2, 'A', 'B'], [3, 4, 'A', 'B'], [5, 'A', 'B']]
Comparison
| Method | Best For | Limitation |
|---|---|---|
| List comprehension with unpacking | Fixed-length sublists | All sublists must have same length |
| + operator with list | Variable-length sublists | Creates nested structure |
| + operator with elements | Adding individual items | None |
Conclusion
Use list comprehension with unpacking for fixed-length sublists, and the + operator for variable-length sublists. Choose based on whether you want nested lists or individual elements added.
