Python | Column deletion from list of lists
Last Updated :
21 Apr, 2023
The problem of removing a row from a list is quite simple and we just need to pop a list out of lists . But there can be a utility where we need to delete a column i.e particular index element of each of the list. This is problem that can occur if we store any database data into containers. Let’s discuss certain ways in which this can be performed.
Method #1 : Using del + loop In this strategy, we just delete the column element one by one using a loop to iterate the row number at each of the iteration.
Python3
test_list = [[ 4 , 5 , 6 , 8 ],
[ 2 , 7 , 10 , 9 ],
[ 12 , 16 , 18 , 20 ]]
print ("The original list is : " + str (test_list))
for j in test_list:
del j[ 1 ]
print ("The modified mesh after column deletion : " + str (test_list))
|
Output :
The original list is : [[4, 5, 6, 8], [2, 7, 10, 9], [12, 16, 18, 20]] The modified mesh after column deletion : [[4, 6, 8], [2, 10, 9], [12, 18, 20]]
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2 : Using pop() + list comprehension We can do this particular task in an easier and shorter way using the list comprehension technique and using the pop function which can be used to remove the list element.
Python3
test_list = [[ 4 , 5 , 6 , 8 ],
[ 2 , 7 , 10 , 9 ],
[ 12 , 16 , 18 , 20 ]]
print ("The original list is : " + str (test_list))
[j.pop( 1 ) for j in test_list]
print ("The modified mesh after column deletion : " + str (test_list))
|
Output :
The original list is : [[4, 5, 6, 8], [2, 7, 10, 9], [12, 16, 18, 20]] The modified mesh after column deletion : [[4, 6, 8], [2, 10, 9], [12, 18, 20]]
Method 3 : using NumPy library.
steps for this approach:
Import the NumPy library.
Convert the list of lists to a NumPy array using the np.array() function.
Use the np.delete() function to delete the column of the NumPy array.
Convert the modified NumPy array back to a list of lists using the tolist() method.
Print the modified mesh after column deletion.
Python3
import numpy as np
test_list = [[ 4 , 5 , 6 , 8 ],
[ 2 , 7 , 10 , 9 ],
[ 12 , 16 , 18 , 20 ]]
print ( "The original list is : " + str (test_list))
test_array = np.array(test_list)
modified_array = np.delete(test_array, 1 , 1 )
modified_list = modified_array.tolist()
print ( "The modified mesh after column deletion : " + str (modified_list))
|
OUTPUT :
The original list is : [[4, 5, 6, 8], [2, 7, 10, 9], [12, 16, 18, 20]]
The modified mesh after column deletion : [[4, 6, 8], [2, 10, 9], [12, 18, 20]]
Time Complexity: O(n*m), where n is the number of rows and m is the number of columns in the original list.
Auxiliary Space: O(n*m), where n is the number of rows and m is the number of columns in the original list.
Share your thoughts in the comments
Please Login to comment...