Python Program to test whether the length of rows are in increasing order

When it is required to test whether the length of rows are in increasing order, a simple iteration and a Boolean value is used. This technique helps verify that each nested list has more elements than the previous one.

Example

my_list = [[55], [12, 17], [25, 32, 24], [58, 36, 57, 19, 14]]

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

my_result = True

for index in range(len(my_list) - 1):
    if len(my_list[index + 1]) <= len(my_list[index]):
        my_result = False
        break

print("The result is :")

if my_result == True:
    print("The rows are increasing in length")
else:
    print("The rows aren't increasing in length")

Output

The list is :
[[55], [12, 17], [25, 32, 24], [58, 36, 57, 19, 14]]
The result is :
The rows are increasing in length

How It Works

The program follows these steps ?

  • A list of nested lists with integers is defined and displayed on the console.
  • A Boolean variable my_result is initialized to True.
  • The list is iterated over, comparing the length of each list with its consecutive list.
  • If any list has length less than or equal to the previous list, my_result is set to False and the loop breaks.
  • Based on the Boolean value, the appropriate message is displayed.

Alternative Approach Using all()

You can also use the all() function for a more concise solution ?

my_list = [[55], [12, 17], [25, 32, 24], [58, 36, 57, 19, 14]]

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

# Check if each row length is greater than previous
is_increasing = all(len(my_list[i]) < len(my_list[i + 1]) 
                   for i in range(len(my_list) - 1))

if is_increasing:
    print("The rows are increasing in length")
else:
    print("The rows aren't increasing in length")
The list is :
[[55], [12, 17], [25, 32, 24], [58, 36, 57, 19, 14]]
The rows are increasing in length

Testing with Non-Increasing Lengths

Let's test with a list where lengths are not increasing ?

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

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

my_result = True

for index in range(len(my_list) - 1):
    if len(my_list[index + 1]) <= len(my_list[index]):
        my_result = False
        break

if my_result:
    print("The rows are increasing in length")
else:
    print("The rows aren't increasing in length")
The list is :
[[1, 2], [3], [4, 5, 6]]
The rows aren't increasing in length

Conclusion

This approach efficiently checks if nested list lengths are in increasing order using simple iteration. The all() function provides a more Pythonic alternative for the same logic.

Updated on: 2026-03-26T00:57:55+05:30

172 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements