DEV Community

Avnish
Avnish

Posted on • Edited on

Python – Check if previous element is smaller in List

Title : Python Check if previous element is smaller in List

To check if the previous element in a list is smaller than the current element, you can iterate through the list and compare each element with its predecessor. Here's an example:

# Example list
numbers = [1, 3, 2, 5, 4]

# Check if the previous element is smaller
for i in range(1, len(numbers)):
    if numbers[i-1] < numbers[i]:
        print(f"{numbers[i-1]} is smaller than {numbers[i]} at index {i}")
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. Start iterating from the second element (i = 1) since the first element (i = 0) doesn't have a previous element.
  2. Compare numbers[i-1] (the previous element) with numbers[i] (the current element).
  3. If the condition is met, perform the desired operation (e.g., print a message or store the indices).

Output:

For the given list [1, 3, 2, 5, 4], the output will be:

1 is smaller than 3 at index 1
2 is smaller than 5 at index 3
Enter fullscreen mode Exit fullscreen mode

You can adapt this approach to suit your specific requirements.

Top comments (0)