Skip to content
Related Articles

Related Articles

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

View Discussion
Improve Article
Save Article
  • Last Updated : 22 Jul, 2022

Given a Matrix, the following program is used to test if length all rows of a matrix are in increasing order or not. If yes, it returns True, otherwise False.

Input : test_list = [[3], [1, 7], [10, 2, 4], [8, 6, 5, 1, 4]] 
Output : True 
Explanation : 1 < 2 < 3 < 5, increasing lengths of rows, hence True.
Input : test_list = [[3], [1, 7], [10], [8, 6, 5, 1, 4]] 
Output : False 
Explanation : 1 <2 >1 < 5, Non-increasing lengths of rows, hence False.

Method 1 : Using loop and len()

In this, we are using loop to check whether the length of next row is greater than the present row, if not, result is flagged off.

Python3




# initializing list
test_list = [[3], [1, 7], [10, 2, 4], [8, 6, 5, 1, 4]]
 
# printing original list
print("The original list is : " + str(test_list))
 
res = True
for idx in range(len(test_list) - 1) :
     
    # flag off in case next length is not greater
    # than current
    if len(test_list[idx + 1]) <= len(test_list[idx]):
        res = False
        break
 
# printing result
print("Are rows of increasing lengths ? : " + str(res))

Output:

The original list is : [[3], [1, 7], [10, 2, 4], [8, 6, 5, 1, 4]]

Are rows of increasing lengths ? : True

Method 2 : Using all() and list comprehension

In this, we test for next length being greater than the current length using len() and all() is used to check for all the rows.

Python3




# initializing list
test_list = [[3], [1, 7], [10, 2, 4], [8, 6, 5, 1, 4]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# checking for truth for all rows in matrix
res = all(len(test_list[idx + 1]) > len(test_list[idx]) for idx in range(len(test_list) - 1))
 
# printing result
print("Are rows of increasing lengths ? : " + str(res))

Output:

The original list is : [[3], [1, 7], [10, 2, 4], [8, 6, 5, 1, 4]]

Are rows of increasing lengths ? : True

Method 3: Using len() and sort()

In this we will append length of each row to a new list, later we will check whether the initial list and  list after sorting are same or not.If same the length of rows are in increasing manner

Python3




# initializing list
test_list = [[3], [1, 7], [10], [8, 6, 5, 1, 4]]
 
# printing original list
print("The original list is : " + str(test_list))
 
res = False
x=[]
for i in test_list:
    x.append(len(i))
a=x
x=x.sort()
if(a==x):
    res=True
# printing result
print("Are rows of increasing lengths ? : " + str(res))

Output

The original list is : [[3], [1, 7], [10], [8, 6, 5, 1, 4]]
Are rows of increasing lengths ? : False

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!