Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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_resultis initialized toTrue. - 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_resultis set toFalseand 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.
Advertisements
