5 Best Ways to Check If a List is Strictly Increasing or Decreasing in Python

Rate this post

πŸ’‘ Problem Formulation: When working with numeric sequences in Python, a common task is to ascertain the nature of a list’s progression. Whether establishing a trend in datasets or validating input, we may need to determine if a list’s elements strictly increase or decrease. A ‘strictly increasing’ list has each element greater than the previous; in a ‘strictly decreasing’ list, each is lesser. For instance, given lists [1, 2, 3] and [3, 2, 1], the program’s output should confirm the former is strictly increasing and the latter is strictly decreasing.

Method 1: Using For Loop and Flag

This method involves iterating over the list with a for loop, comparing each element to its predecessor to determine if the sequence is strictly increasing or decreasing. A flag variable is used to track whether the list violates either condition.

Here’s an example:

def is_strictly_monotonic(lst):
    increasing = decreasing = True
    for i in range(1, len(lst)):
        if lst[i] <= lst[i - 1]:
            increasing = False
        if lst[i] >= lst[i - 1]:
            decreasing = False
    return increasing or decreasing

# Example usage:
print(is_strictly_monotonic([1, 3, 5]))  # Output: True
print(is_strictly_monotonic([5, 3, 1]))  # Output: True
print(is_strictly_monotonic([1, 2, 2]))  # Output: False

The function is_strictly_monotonic() determines whether a given list is either strictly increasing or decreasing. By initially assuming that the list is both increasing and decreasing, we iterate through the list elements and invalidate one or both assumptions as necessary. The result is a Boolean indicating whether the list maintains one of the strict conditions.

Method 2: Using Python’s all() Function

The all() function in Python checks if all elements in an iterable satisfy a certain condition. This method employs all() in conjunction with a generator expression to identify if a list is strictly increasing or decreasing succinctly.

Here’s an example:

def is_strictly_monotonic(lst):
    return all(lst[i] < lst[i+1] for i in range(len(lst) - 1)) or \
           all(lst[i] > lst[i+1] for i in range(len(lst) - 1))

# Example usage:
print(is_strictly_monotonic([7, 10, 11]))  # Output: True
print(is_strictly_monotonic([14, 9, 3]))   # Output: True
print(is_strictly_monotonic([1, 5, 3]))    # Output: False

The function is_strictly_monotonic() leverages the all() function to affirm that each list element (except the last) is less than or greater than the next one. This concise method enables quick identification of strictly monotonic sequences.

Method 3: Using Differences

We can determine the nature of a list’s progression by evaluating the sign of the difference between consecutive elements. If all differences are positive, the list is strictly increasing; if all are negative, it is strictly decreasing.

Here’s an example:

def is_strictly_monotonic(lst):
    diffs = [lst[i + 1] - lst[i] for i in range(len(lst) - 1)]
    return all(diff > 0 for diff in diffs) or all(diff < 0 for diff in diffs)

# Example usage:
print(is_strictly_monotonic([2, 4, 8]))    # Output: True
print(is_strictly_monotonic([100, 50, 20])) # Output: True
print(is_strictly_monotonic([3, 3, 5]))    # Output: False

The function is_strictly_monotonic() first computes a list of differences between consecutive elements. It then uses two all() checks to ascertain the sign consistency of these differences and thus the nature of the list’s trend.

Method 4: Using itertools and operator

By leveraging two standard library modules, itertools and operator, we can create a compact solution. The pairwise() function from itertools and the comparison operators as functions from operator make comparisons within a map function elegant and concise.

Here’s an example:

from itertools import pairwise
from operator import lt, gt

def is_strictly_monotonic(lst):
    return all(map(lt, lst, lst[1:])) or all(map(gt, lst, lst[1:]))

# Example usage:
print(is_strictly_monotonic([10, 20, 30])) # Output: True
print(is_strictly_monotonic([30, 20, 10])) # Output: True
print(is_strictly_monotonic([7, 8, 8, 9])) # Output: False

The function is_strictly_monotonic() captures the essence of Python’s functional programming capabilities. By mapping the less than (lt) and greater than (gt) functions across pairs of list items, we discern the strict increasing or decreasing nature of the list in a highly readable manner.

Bonus One-Liner Method 5: Using List Comprehension And Comparison

A Python one-liner may use list comprehension to produce a Boolean value that reflects whether a list is strictly increasing or decreasing. This method typically compresses the logic from previous examples into a single, albeit complex, line of code.

Here’s an example:

is_strictly_monotonic = lambda lst: all(lst[i] < lst[i+1] for i in range(len(lst)-1)) or all(lst[i] > lst[i+1] for i in range(len(lst)-1))

# Example usage:
print(is_strictly_monotonic([1, 2, 3]))  # Output: True
print(is_strictly_monotonic([3, 2, 1]))  # Output: True
print(is_strictly_monotonic([5, 5, 5]))  # Output: False

This concise one-liner employs a lambda function with list comprehension to check strictly increasing or decreasing conditions, showcasing Python’s capability for writing condensed and efficient code.

Summary/Discussion

  • Method 1: Using For Loop and Flag. Easy to understand for beginners. Not the most Pythonic solution. Can be verbose.
  • Method 2: Using Python’s all() Function. Compact and Pythonic. Requires understanding of advanced concepts like generator expressions.
  • Method 3: Using Differences. Mathematical approach making it easily translatable to other programming languages. May be less performant due to list creation for differences.
  • Method 4: Using itertools and operator. Makes code terse and clean. Depends on Python’s standard libraries which may not be familiar to all programmers.
  • Method 5: Bonus One-Liner. Extremely compact. Could be less readable to those unfamiliar with Python’s terse expressive power.