DEV Community

Avnish
Avnish

Posted on

Python – Check if previous element is smaller in List

Title : Python Check if previous element is smaller in List

Method 1: Using a Loop

def check_prev_smaller_loop(test_list):
    res = []
    for idx in range(1, len(test_list)):
        res.append(test_list[idx - 1] < test_list[idx])
    return res
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Function Definition: This method defines a function named check_prev_smaller_loop that takes a list test_list as its argument.
  • Initialize Result List: An empty list res is initialized to store the results.
  • Loop Through the List: The function then loops through the list, starting from the second element (index 1) to the end of the list. For each element, it checks if the previous element (test_list[idx - 1]) is smaller than the current element (test_list[idx]).
  • Append Result: If the previous element is smaller, True is appended to res; otherwise, False is appended.
  • Return Result: Finally, the res list, which contains the result of the comparison for each element (excluding the first), is returned.

Method 2: Using zip() + List Comprehension

def check_prev_smaller_zip(test_list):
    return [sub1 < sub2 for sub1, sub2 in zip(test_list, test_list[1:])]
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Function Definition: A function check_prev_smaller_zip is defined, accepting test_list as an argument.
  • Use of zip() and List Comprehension: This line returns the result of a list comprehension that iterates over pairs of adjacent elements in test_list. The zip(test_list, test_list[1:]) call creates tuples of each element and its next element. For example, if test_list is [1, 2, 3], zip() would produce [(1, 2), (2, 3)].
  • Comparison and Return: For each tuple (sub1, sub2), it compares sub1 (the current element in the original list) with sub2 (the next element) and returns True if sub1 is less than sub2, otherwise False. The result is a list of Boolean values corresponding to each comparison, which is immediately returned.

Method 3: Using the map() Function

def check_prev_smaller_map(test_list):
    return list(map(lambda i: i[0] < i[1], zip(test_list[:-1], test_list[1:])))
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Function Definition: Defines a function check_prev_smaller_map that takes test_list as input.
  • Use of map() and zip(): This method utilizes the map() function, which applies a function to every item of an iterable (in this case, tuples of adjacent elements created by zip()) and returns a map object. The zip(test_list[:-1], test_list[1:]) call creates tuples of each element with its next element, excluding the first and last elements respectively to align the pairs correctly.
  • Lambda Function for Comparison: A lambda function is used to compare the first element of each tuple (i[0]) with the second element (i[1]). If the first element is smaller, the lambda function returns True; otherwise, it returns False.
  • Conversion to List and Return: The result of the map() function is converted to a list using list() and is immediately returned. This list contains the comparison results for each pair of adjacent elements in the original list.

Testing the Functions

test_list = [6, 3, 7, 3, 6, 7, 8, 3]
print("Using loop:", check_prev_smaller_loop(test_list))
print("Using zip() + list comprehension:", check_prev_smaller_zip(test_list))
print("Using map() function:", check_prev_smaller_map(test_list))
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • A test list is defined, and each of the three functions is called with this list as the argument. The results of these calls are printed to the console, demonstrating how each function performs the task of checking if the previous element is smaller than the current element in the list.

Each method offers a different approach to solving the same problem, showcasing the flexibility and power of Python for data manipulation and comparison tasks.

Top comments (0)