+

Python | Remove the last element from every row in a matrix

Method # 1: Using a loop + del + slicing list
A combination of the above functions can be used to accomplish this task. In this we run a loop for each row in the matrix and remove the trailing element using del .

# Python3 code to demonstrate how it works
# Remove the last element from each row in the matrix
# Using a loop + Del + slicing list

 
# initialize the list

test_list = [[[ 1 , 3 , 4 ], [ 2 , 4 , 6 ], [ 3 , 8 , 1 ]]

 
# print original list

print ( "The original list:" + str (test_list))

 
# Remove the last element from each row in the matrix
# Using a loop + Del + slicing list

for ele in test_list: del ele [ -  1

 
# print result

print ( "Matrix after removal of rear element from rows: " + str (test_list) )

Output:

 The original list: [[1, 3, 4], [2, 4, 6], [3, 8, 1]] Matrix after removal of rear element from rows: [[1, 3], [2, 4], [ 3, 8]] 

Method # 2: Using List Comprehension + List Slicing
A combination of the above functions can also be used to accomplish this task. In this we simply iterate over each row and remove the trailing element using the list slicing.

# Python3 code to demonstrate how it works
# Remove the last element from each row in the matrix
# Using list comprehension + list slicing

 
# initialize the list

test_list = [[ 1 , 3 , 4 ], [ 2 , 4 , 6 ], [ 3 , 8 , 1 ]]

  
# print the original list

print ( " The original list: " + str (test_list))

 
# Remove the last element from each row in the matrix
# Using list comprehension + list slicing

res = [ele [: - 1 ] for ele in test_list]

 
# print result

print ( "Matrix after removal of rear element from rows:" + str (res))

Output:

 The original list: [[1, 3, 4], [2, 4, 6], [3, 8, 1]] Matrix after removal of rear element from rows: [[1, 3], [2, 4], [3, 8]] 
Get Solution for free from DataCamp guru