Adding value to sublists in Python

PythonServer Side ProgrammingProgramming

Sometimes we need to introduce an additional value to an already existing list. In this article we will see how the new value or values can be inserted into an already existing list by combining with each item of the existing list.

Using For Loop

If we take a list which has items of the same length, we can use this method to introduce new values in each of the item of the list. In the below example we are taking a list of

Example

 Live Demo

List = [[10, 20], [14, 8],['Mon','Tue']]
print("Given List: \n" + str(List))
s = "Rise"
t = "fast"
result = [[m, n, s,t ] for m, n in List]
#result
print("\nNew List: \n" + str(result))

Running the above code gives us the following result

Output

Given List:
[[10, 20], [14, 8], ['Mon', 'Tue']]
New List:
[[10, 20, 'Rise', 'fast'], [14, 8, 'Rise', 'fast'], ['Mon', 'Tue', 'Rise', 'fast']]

Using + Operator

The + operator when used with a list simply adds new elements to each of the list items. In the below example we find that even a list itself can be used as a new element to be added to the existing lift. Also the existing elements in the list can be of varying length.

Example

 Live Demo

List = [[1.5, 2.5, 'Tue'], [0.8, 0.9, 'Ocean'], [6.8, 4.3], [9]]
print("Given List: \n" + str(List))
# Choose a list to be added.
s = ["Rise","Fast"]
result = [sub + [s] for sub in List]
print("\nNew List: \n" + str(result))

Running the above code gives us the following result

Output

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']]]
raja
Published on 23-Dec-2019 10:33:19
Advertisements