Python - Check if previous element is smaller in List
Last Updated :
02 May, 2023
Sometimes, while working with Python lists, we can have a problem in which we need to check for each element if its preceding element is smaller. This type of problem can have its use in data preprocessing domains. Let's discuss certain problems in which this task can be performed.
Input : test_list = [1, 3, 5, 6, 8]
Output : [True, True, True, True]
Input : test_list = [3, 1]
Output : [False]
Method #1 : Using loop
This is one of the ways in which this task can be performed. In this, we perform the task of checking for elements using brute for in loop.
Python3
# Python3 code to demonstrate working of
# Check if previous element is smaller in List
# Using loop
# initializing list
test_list = [6, 3, 7, 3, 6, 7, 8, 3]
# printing original list
print("The original list is : " + str(test_list))
# Check if previous element is smaller in List
# Using loop
res = []
for idx in range(1, len(test_list)):
if test_list[idx - 1] < test_list[idx]:
res.append(True)
else:
res.append(False)
# printing result
print("List after filtering : " + str(res))
Output : The original list is : [6, 3, 7, 3, 6, 7, 8, 3]
List after filtering : [False, True, False, True, True, True, False]
Time complexity: O(n), where n is the length of the input list.
Auxiliary Space: O(n), where n is the length of the input list. This is because the program creates a list of the same length as the input list to store the results.
Method #2 : Using zip() + list comprehension
This is one-liner approach to solve this problem. In this, we first, zip the list and its next element list, and then check for comparisons for result.
Python3
# Python3 code to demonstrate working of
# Check if previous element is smaller in List
# Using zip() + list comprehension
# initializing list
test_list = [6, 3, 7, 3, 6, 7, 8, 3]
# printing original list
print("The original list is : " + str(test_list))
# Check if previous element is smaller in List
# Using zip() + list comprehension
res = [int(sub1) < int(sub2) for sub1, sub2 in zip(test_list, test_list[1:])]
# printing result
print("List after filtering : " + str(res))
Output : The original list is : [6, 3, 7, 3, 6, 7, 8, 3]
List after filtering : [False, True, False, True, True, True, False]
The time complexity of the given code is O(n), where n is the length of the input list.
The auxiliary space complexity of the given code is O(n),
Method 3 : Using the built-in map() function
Steps :
- The first line imports the itertools module which provides various functions to work with iterators and combinatorial iterators.
- The second line initializes a list named "test_list" with some values.
- The third line prints the original list using the print() function.
- The fourth line uses the map() function to check if the previous element is smaller in the list.
- The map() function applies a lambda function to each element of the iterable object. In this case, it applies the lambda function to each pair of adjacent elements in the list using the zip() function. The lambda function returns True if the first element of the pair is greater than the second element, otherwise it returns False.
- The zip() function takes two or more iterables and returns an iterator of tuples containing elements from each iterable. In this case, it takes the test_list from the second element to the end (test_list[1:]) and the test_list from the beginning to the second to last element (test_list[:-1]) and returns an iterator of tuples containing pairs of adjacent elements in the original list.
- The result of the map() function is a map object, which is an iterator that applies the lambda function to each element of the iterable object.
- The result is converted to a list using the list() function and stored in the variable "res".
- The last line prints the filtered list using the print() function
Python3
# Python3 code to demonstrate working of
# Check if previous element is smaller in List
# Using map() function
# initializing list
test_list = [6, 3, 7, 3, 6, 7, 8, 3]
# printing original list
print("The original list is : " + str(test_list))
# Check if previous element is smaller in List
# Using map() function
res = list(map(lambda i: i[0] > i[1], zip(test_list[1:], test_list)))
# printing result
print("List after filtering : " + str(res))
OutputThe original list is : [6, 3, 7, 3, 6, 7, 8, 3]
List after filtering : [False, True, False, True, True, True, False]
Time complexity: The zip() function and the map() function both iterate over the list once, so the time complexity of this approach is O(n).
Auxiliary space: We create a new list to store the filtered values, so the auxiliary space complexity of this approach is O(n).
Similar Reads
Python - Check if element is present in tuple We are given a tuple and our task is to find whether given element is present in tuple or not. For example x = (1, 2, 3, 4, 5) and we need to find if 3 is present in tuple so that in this case resultant output should be True.Using in Operatorin operator checks if an element is present in a tuple by
2 min read
Python - Check if all elements in List are same To check if all items in list are same, we have multiple methods available in Python. Using SetUsing set() is the best method to check if all items are same in list. Pythona = [3, 3, 3, 3] # Check if all elements are the same result = len(set(a)) == 1 print(result) OutputTrue Explanation:Converting
3 min read
Python | Check if any element occurs n times in given list Given a list, the task is to find whether any element occurs 'n' times in given list of integers. It will basically check for the first element that occurs n number of times. Examples: Input: l = [1, 2, 3, 4, 0, 4, 3, 2, 1, 2], n = 3 Output : 2 Input: l = [1, 2, 3, 4, 0, 4, 3, 2, 1, 2, 1, 1], n = 4
5 min read
Python - Check if List contains elements in Range Checking if a list contains elements within a specific range is a common problem. In this article, we will various approaches to test if elements of a list fall within a given range in Python. Let's start with a simple method to Test whether a list contains elements in a range.Using any() Function -
3 min read
Last Occurrence of Some Element in a List - Python We are given a list we need to find last occurrence of some elements in list. For example, w = ["apple", "banana", "orange", "apple", "grape"] we need to find last occurrence of string 'apple' so output will be 3 in this case.Using rindex()rindex() method in Python returns the index of the last occu
3 min read
Python - Check Similar elements in Matrix rows Given a Matrix and list, the task is to write a Python program to check if all the matrix elements of the row are similar to the ith index of the List. Input : test_list = [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]] Output : True Explanation : All rows have same elements.Input : test_list = [[1, 1,
8 min read
Python | Remove given element from list of lists The deletion of elementary elements from list has been dealt with many times, but sometimes rather than having just a one list, we have list of list where we need to perform this particular task. Having shorthands to perform this particular task can help. Let's discuss certain ways to perform this p
6 min read
Check if any element in list satisfies a condition-Python The task of checking if any element in a list satisfies a condition involves iterating through the list and returning True if at least one element meets the condition otherwise, it returns False. For example, in a = [4, 5, 8, 9, 10, 17], checking ele > 10 returns True as 17 satisfies the conditio
2 min read
Python - Check alternate peak elements in List Given a list, the task is to write a Python program to test if it's alternate, i.e next and previous elements are either both smaller or larger across the whole list. Input : test_list = [2, 4, 1, 6, 4, 8, 0] Output : True Explanation : 4, 6, 8 are alternate and peaks (2 1). Input : test_list = [2,
3 min read
Python - Elements Maximum till current index in List Given list with elements, extract element if it's the maximum element till current index. Input : test_list = [4, 6, 7, 8] Output : [4, 6, 7, 8] Explanation : All elements are maximum till their index. Input : test_list = [6, 7, 3, 6, 8, 7] Output : [7, 8] Explanation : 7 and 8 are maximum till thei
7 min read