Python | Adding value to sublists
Last Updated :
31 Mar, 2023
Sometimes, we just have to manipulate a list of lists by appending a similar value to all the sublists. Using a loop for achieving this particular task can be an option but sometimes leads to sacrificing the readability of code. It is always wanted to have a oneliner to perform this particular task. Let’s discuss certain ways in which this can be done.
Method #1: Using list comprehension can be used to perform this particular task using a similar looping construct but in just a single line. This increases code readability.
Python3
test_list = [[ 1 , 3 ], [ 3 , 4 ], [ 6 , 5 ], [ 4 , 5 ]]
print ( "The original list : " + str (test_list))
K = "GFG"
res = [[i, j, K] for i, j in test_list]
print ( "The list after adding element : " + str (res))
|
Output
The original list : [[1, 3], [3, 4], [6, 5], [4, 5]]
The list after adding element : [[1, 3, 'GFG'], [3, 4, 'GFG'], [6, 5, 'GFG'], [4, 5, 'GFG']]
Time complexity: O(n), where n is the number of elements in the original list (test_list).
Auxiliary space: O(n), as a new list (res) is created with the same number of elements as the original list.
Method #2 : Using list comprehension + “+” operator This method is quite similar to the above method, but the difference is that plus operator is used to add the new element to each sublist.
Python3
test_list = [[ 1 , 3 ], [ 3 , 4 ], [ 6 , 5 ], [ 4 , 5 ]]
print ( "The original list : " + str (test_list))
K = "GFG"
res = [sub + [K] for sub in test_list]
print ( "The list after adding element : " + str (res))
|
Output
The original list : [[1, 3], [3, 4], [6, 5], [4, 5]]
The list after adding element : [[1, 3, 'GFG'], [3, 4, 'GFG'], [6, 5, 'GFG'], [4, 5, 'GFG']]
Time complexity: O(n) where n is the number of sublists in the test_list.
Auxiliary space: O(n) for the new list ‘res’ created using the list comprehension.
Method #3 : Using for loop
Python3
test_list = [[ 1 , 3 ], [ 3 , 4 ], [ 6 , 5 ], [ 4 , 5 ]]
print ( "The original list : " + str (test_list))
K = "GFG"
res = []
for i in test_list:
i.append(K)
res.append(i)
print ( "The list after adding element : " + str (res))
|
Output
The original list : [[1, 3], [3, 4], [6, 5], [4, 5]]
The list after adding element : [[1, 3, 'GFG'], [3, 4, 'GFG'], [6, 5, 'GFG'], [4, 5, 'GFG']]
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list.
Method #4: Using map() and lambda function
Here is the approach using map() and lambda function
Python3
test_list = [[ 1 , 3 ], [ 3 , 4 ], [ 6 , 5 ], [ 4 , 5 ]]
print ( "The original list : " + str (test_list))
K = "GFG"
res = list ( map ( lambda x: x + [K], test_list))
print ( "The list after adding element : " + str (res))
|
Output
The original list : [[1, 3], [3, 4], [6, 5], [4, 5]]
The list after adding element : [[1, 3, 'GFG'], [3, 4, 'GFG'], [6, 5, 'GFG'], [4, 5, 'GFG']]
Time complexity: O(n)
Auxiliary Space: O(n)
Method #5: Using itertools.chain and zip:
Python3
import itertools
test_list = [[ 1 , 3 ], [ 3 , 4 ], [ 6 , 5 ], [ 4 , 5 ]]
K = "GFG"
print ( "The original list : " + str (test_list))
res = [ list (itertools.chain(i, [K])) for i in test_list]
print ( "The list after adding element : " + str (res))
|
Output
The original list : [[1, 3], [3, 4], [6, 5], [4, 5]]
The list after adding element : [[1, 3, 'GFG'], [3, 4, 'GFG'], [6, 5, 'GFG'], [4, 5, 'GFG']]
Time complexity: O(n)
Auxiliary Space: O(n*k)
Method #6: Using numpy
To use numpy we need to install it first. You can install it using the following command: pip install numpy
Step by step approach:
- Import numpy module using import numpy as np
- Convert test_list into numpy array using np.array(test_list)
- Append the value ‘K’ to the numpy array using np.append()
- Reshape the numpy array to the original shape using .reshape() method
- Convert the numpy array back to list using .tolist() method
Python3
import numpy as np
test_list = [[ 1 , 3 ], [ 3 , 4 ], [ 6 , 5 ], [ 4 , 5 ]]
print ( "The original list : " + str (test_list))
K = "GFG"
test_np = np.array(test_list)
res_np = np.append(test_np, np.full(( len (test_list), 1 ), K), axis = 1 ).reshape( len (test_list), - 1 ).tolist()
print ( "The list after adding element : " + str (res_np))
|
Output:
The original list : [[1, 3], [3, 4], [6, 5], [4, 5]]
The list after adding element : [['1', '3', 'GFG'], ['3', '4', 'GFG'], ['6', '5', 'GFG'], ['4', '5', 'GFG']]
Time complexity: O(n) (where n is the number of elements in the list)
Auxiliary space: O(n) (for creating a numpy array)
Method #7: Using extend() method inside a for loop
Use a for loop to iterate through each sublist of the original list.
Use the extend() method to append the value to each sublist.
Python3
test_list = [[ 1 , 3 ], [ 3 , 4 ], [ 6 , 5 ], [ 4 , 5 ]]
K = "GFG"
for sublist in test_list:
sublist.extend([K])
print ( "The list after adding element : " + str (test_list))
|
Output
The list after adding element : [[1, 3, 'GFG'], [3, 4, 'GFG'], [6, 5, 'GFG'], [4, 5, 'GFG']]
Time complexity: O(n), where n is the length of the list.
Auxiliary space: O(1), because no additional data structure is created.
Similar Reads
Python | Indexing a sublist
In Python, we have several ways to perform the indexing in list, but sometimes, we have more than just an element to index, the real problem starts when we have a sublist and its element has to be indexed. Let's discuss certain ways in which this can be performed. Method #1 : Using index() + list co
3 min read
Python | Maximum Sum Sublist
The task is to find a contiguous sublist (i.e., a sequence of elements that appear consecutively in the original list) such that the sum of the elements in this sublist is as large as possible. We need to return the maximum sum of this sublist. Let's explore methods to find Maximum Sum Sublist in py
2 min read
How to Add Values to Dictionary in Python
The task of adding values to a dictionary in Python involves inserting new key-value pairs or modifying existing ones. A dictionary stores data in key-value pairs, where each key must be unique. Adding values allows us to expand or update the dictionary's contents, enabling dynamic manipulation of d
3 min read
Python program to find the sum of a Sublist
Given a list of numbers, write a Python program to find the sum of all the elements in the list. Examples: Input: arr = [2,4,5,10], i = 1, j = 3Output: 19Input: arr = [4,10,5,3,3], i = 3, j = 3Output: 3Find the sum of a Sublist Applying Brute Force In this method, we will be initializing an output v
3 min read
Python - Index Value Summation List
To access the elements of lists, there are various methods. But sometimes we may require to access the element along with the index on which it is found and compute its summation, and for that, we may need to employ different strategies. This article discusses some of those strategies. Method 1: Nai
4 min read
Python - Incremental Sublist Sum
Sometimes we need to group elements and grouping techniques and requirements vary accordingly. One such way to group the elements is by the iâth size in list which stores the dictionary of index keys with values of summation of subsequent size i. Letâs discuss certain ways in which this can be done.
3 min read
Python - Dictionary Tuple Values Update
The task of updating tuple values in a dictionary involves modifying each tuple in the dictionary by applying a specific operation to its elements. In this case, the goal is to update each element of the tuple based on a given condition, such as multiplying each element by a constant. For example, g
3 min read
Append a Value to a Dictionary Python
The task of appending a value to a dictionary in Python involves adding new data to existing key-value pairs or introducing new key-value pairs into the dictionary. This operation is commonly used when modifying or expanding a dictionary with additional information. For example, consider the diction
3 min read
Python - Add Values to Dictionary of List
A dictionary of lists allows storing grouped values under specific keys. For example, in a = {'x': [10, 20]}, the key 'x' maps to the list [10, 20]. To add values like 30 to this list, we use efficient methods to update the dictionary dynamically. Letâs look at some commonly used methods to efficien
3 min read
Python | Add similar value multiple times in list
Adding a single value in list is quite generic and easy. But to add that value more than one time, generally, a loop is used to execute this task. Having shorter tricks to perform this can be handy. Let's discuss certain ways in which this can be done. Method #1 : Using * operator We can employ * op
5 min read