Add custom borders to a matrix in Python


When it is required to add custom borders to the matrix, a simple list iteration can be used to add the required borders to the matrix.

Example

Below is a demonstration of the same

my_list = [[2, 5, 5], [2, 7, 5], [4, 5, 1], [1, 6, 6]]

print("The list is :")
print(my_list)

print("The resultant matrix is :")

border = "|"

for sub in my_list:
   my_temp = border + " "

   for ele in sub:
      my_temp = my_temp + str(ele) + " "

   my_temp = my_temp + border
   print(my_temp)

Output

The list is :
[[2, 5, 5], [2, 7, 5], [4, 5, 1], [1, 6, 6]]
The resultant matrix is :
| 2 5 5 |
| 2 7 5 |
| 4 5 1 |
| 1 6 6 |

Explanation

  • A list of list is defined and is displayed on the console.

  • A value for the ‘border’ is defined.

  • The list is iterated over, and this border is concatenated to a space.

  • The elements are iterated over and this border is concatenated with them.

  • This is displayed as result on the console.

Updated on: 21-Sep-2021

202 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements