Remove a specific column from a List of lists in Python

This tutorial will discuss how to remove a specific column from a list of lists in Python.

Suppose we have a matrix, represented as a list of lists. Like this,

sampleMatrix = [[11, 22, 33, 44, 55],
                [11, 22, 33, 44, 55],
                [11, 22, 33, 44, 55]]

Now, let’s say we want to remove a specific column from this matrix. For instance, if we aim to remove the second column (i.e., column at index 1), we can iterate through each row of the matrix. For each row, we’ll construct a new row excluding the element at the desired index (in this case, the second element). To facilitate this, we’ve created a dedicated function.

def removeColumn(matrix, columnIndex):
    # Using list comprehension to remove the specified column
    return [row[:columnIndex] + row[columnIndex+1:] for row in matrix]

This function takes in two arguments: the matrix (as a list of lists) as the first argument, and the column index to be removed as the second. This function then effectively eliminates the specified column from the matrix. Using list comprehension, the task becomes even more streamlined.

For practical application, if we want to remove the second column from a given matrix, we simply call this function. By providing the matrix as the first argument and the column index (1 in this case) as the second, the function will efficiently excise the second column from the matrix.

Let’s see the complete example,

def removeColumn(matrix, columnIndex):
    # Using list comprehension to remove the specified column
    return [row[:columnIndex] + row[columnIndex+1:] for row in matrix]

# A List of List
sampleMatrix = [[11, 22, 33, 44, 55],
                [11, 22, 33, 44, 55],
                [11, 22, 33, 44, 55]]

# Index of Column that needs to be deleted
colIndex = 1

print("Original Matrix:")
for row in sampleMatrix:
    print(row)

# Remove 2nd Column from List of List i.e. column at index 1
sampleMatrix = removeColumn(sampleMatrix, colIndex)

print("nMatrix after removing column", colIndex, ":")
for row in sampleMatrix:
    print(row)

Output

Original Matrix:
[11, 22, 33, 44, 55]
[11, 22, 33, 44, 55]
[11, 22, 33, 44, 55]

Matrix after removing column 1 :
[11, 33, 44, 55]
[11, 33, 44, 55]
[11, 33, 44, 55]

Summary

Today, we learned how to remove a specific column from a list of lists in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top