Given a list, the task here is to write a Python program to replace its elements after comparing them with another number here described using K.
For the example depicted in this article, any number greater than K will be replaced with the value given in high and any number less than or equal to K will be replaced with the value given in low.
Input : test_list = [7, 4, 3, 2, 6, 8, 9, 1], low = 2, high = 9, K = 5
Output : [9, 2, 2, 2, 9, 9, 9, 2]
Explanation : Elements less than K substituted by 2, rest are by 9.
Input : test_list = [7, 4, 3, 2, 6, 8, 9, 1], low =2, high = 8, K = 5
Output : [8, 2, 2, 2, 8, 8, 8, 2]
Explanation : Elements less than K substituted by 2, rest are by 8.
In this, we perform replacements using conditional statements and iteration is performed using loop.
The original list is : [7, 4, 3, 2, 6, 8, 9, 1]
List after replacement ? : [9, 2, 2, 2, 9, 9, 9, 2]
Similar to the method above, only difference is this is a one liner solution and a compact alternative using list comprehension.
The original list is : [7, 4, 3, 2, 6, 8, 9, 1]
List after replacement ? : [9, 2, 2, 2, 9, 9, 9, 2]
Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.
OutputThe original list is : [7, 4, 3, 2, 6, 8, 9, 1]
List after replacement: [9, 2, 2, 2, 9, 9, 9, 2]