Python Program to convert a list into matrix with size of each row increasing by a number

When it is required to convert a list into a matrix with the size of every row increasing by a number, the floor division operator // and list slicing are used together with iteration.

Example

Below is a demonstration of the same −

my_list = [42, 45, 67, 89, 99, 10, 23, 12, 31, 43, 60, 1, 0]

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

my_key = 3
print("The value of key is")
print(my_key)

my_result = []

for index in range(0, len(my_list) // my_key):
    my_result.append(my_list[0: (index + 1) * my_key])

print("The resultant matrix is :")
print(my_result)

Output

The list is :
[42, 45, 67, 89, 99, 10, 23, 12, 31, 43, 60, 1, 0]
The value of key is
3
The resultant matrix is :
[[42, 45, 67], [42, 45, 67, 89, 99, 10], [42, 45, 67, 89, 99, 10, 23, 12, 31], [42, 45, 67, 89, 99, 10, 23, 12, 31, 43, 60, 1]]

How It Works

The algorithm works by creating rows of increasing size using list slicing ?

  • Row 1: Elements 0 to 3 (1 × key)

  • Row 2: Elements 0 to 6 (2 × key)

  • Row 3: Elements 0 to 9 (3 × key)

  • Row 4: Elements 0 to 12 (4 × key)

Alternative Approach Using List Comprehension

The same result can be achieved more concisely using list comprehension ?

my_list = [42, 45, 67, 89, 99, 10, 23, 12, 31, 43, 60, 1, 0]
my_key = 3

my_result = [my_list[0:(i + 1) * my_key] for i in range(len(my_list) // my_key)]

print("The resultant matrix is :")
print(my_result)
The resultant matrix is :
[[42, 45, 67], [42, 45, 67, 89, 99, 10], [42, 45, 67, 89, 99, 10, 23, 12, 31], [42, 45, 67, 89, 99, 10, 23, 12, 31, 43, 60, 1]]

Key Points

  • The // operator calculates how many complete rows can be formed

  • List slicing [0:(index + 1) * my_key] creates rows of increasing length

  • Each row contains all elements from the beginning up to a certain position

  • The key value determines the increment size for each row

Conclusion

This approach converts a list into a matrix where each row grows by a fixed increment. The floor division operator determines the number of rows, while list slicing creates progressively larger rows.

Updated on: 2026-03-26T02:18:25+05:30

508 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements