Python | Check if the list is growing strictly

Python Methods and Functions

Method # 1: Using all () + zip ()
The all () function usually checks all elements passed to her. The zip () task — concatenate the list starting at the beginning and the list starting at the first element so that all elements can be checked.

# Python3 demo code
# check strictly increasing list
# using zip () + all ()

 
# initializing list

test_list = [ 1 , 4 , 5 , 7 , 8 , 10 ]

  
# print original lists

print ( "Original list:" + str (test_list))

  
# using zip () + all ()
# check strictly increasing list

res = all (i & lt; j for i, j in zip (test_list, test_list [ 1 :]) )

 
# print result

print ( "Is list strictly increasing?:" + str (res))

Exit:

 Original list: [1, 4, 5, 7, 8, 10] Is list strictly increasing? : True 

Method # 2: Using reduce () + lambda
reduce () combined with lambda can also perform this monotony test task. Reduce function is used to accumulate the result as True or False, the lambda function checks each index value with the next index value.

# Python3 demo code
# check strictly increasing list
# using Reduce () + lambda

 
# initializing list

test_list = [ 1 , 4 , 5 , 7 , 8 , 10 ]

 
# printing original lists

print ( "Original list:" + str (test_list))

 
# using Reduce () + lambda
# check strictly increasing list

res = bool ( lambda test_list: reduce ( lambda i, j: j if  

i & lt; j else 9999 , test_list)! = 9999 )

 
# print result

print ( " Is list strictly increasing?: " + str (res))

Output:

 Original list: [1, 4, 5, 7, 8, 10] Is list strictly increasing? : True 

Method # 3: Using itertools.starmap () + zip () + all ()
Another method to do of this task, starmap () associates the operation with the archived lists as in method 1, and all () also performs the same task of cumulating the result.

# Python3 demo code
# check strictly incremental list
# using itertools.starmap () + zip () + all ()

import operator

import itertools

 
# initializing list

test_list = [ 1 , 4 , 5 , 7 , 8 , 10 ]

 
# printing original lists

print ( "Original list:" + str (test_list))

 
# using itertools.starmap () + zip () + all ()
# check strictly increasing list

res all (itertools.starmap (operator.le, 

  zip (test_list, test_list [ 1 :])))

 
# print result

print ( "Is list strictly increasing? : " + str (res))

Exit:

 Original list: [1, 4, 5 , 7, 8, 10] Is list strictly increasing?: True 




Get Solution for free from DataCamp guru