Python - Column deletion from list of lists


In a list of lists an element at the same index of each of the sublist represents a column like structure. In this article we will see how we can delete a column from a list of lists. Which means we have to delete the element at the same index position from each of the sublist.

Using pop

We use the pop method which removes the element at a particular position. A for loop is designed to iterate through elements at specific index and removes them using pop.

Example

 Live Demo

# List of lists
listA = [[3, 9, 5, 1],
[4, 6, 1, 2],
[1, 6, 12, 18]]

# printing original list
print("Given list \n",listA)

# Apply pop
[i.pop(2) for i in listA]

# Result
print("List after deleting the column :\n ",listA)

Output

Running the above code gives us the following result −

Given list
[[3, 9, 5, 1], [4, 6, 1, 2], [1, 6, 12, 18]]
List after deleting the column :
[[3, 9, 1], [4, 6, 2], [1, 6, 18]]

With del

In this approach we use the del function which is similar to above approach. We mention the index at which the column has to be deleted.

Example

 Live Demo

# List of lists
listA = [[3, 9, 5, 1],
[4, 6, 1, 2],
[1, 6, 12, 18]]

# printing original list
print("Given list \n",listA)

# Apply del
for i in listA:
del i[2]

# Result
print("List after deleting the column :\n ",listA)

Output

Running the above code gives us the following result −

Given list
[[3, 9, 5, 1], [4, 6, 1, 2], [1, 6, 12, 18]]
List after deleting the column :
[[3, 9, 1], [4, 6, 2], [1, 6, 18]]

Updated on: 10-Jul-2020

842 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements