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}")
Explanation:
- Start iterating from the second element (
i = 1
) since the first element (i = 0
) doesn't have a previous element. - Compare
numbers[i-1]
(the previous element) withnumbers[i]
(the current element). - 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
You can adapt this approach to suit your specific requirements.
Top comments (0)