- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Program to replace elements of a list based on the comparison with a number
When it is required to replace elements of a list based on the comparison with a number, a simple iteration is used.
Below is a demonstration of the same
my_list = [32, 37, 44, 38, 92, 61, 28, 92, 20] print("The list is :") print(my_list) my_key = 32 print("The key is ") print(my_key) low, high = 2, 9 my_result =  for ele in my_list: if ele > my_key: my_result.append(high) else: my_result.append(low) print("The resultant list is :") print(my_result)
The list is : [32, 37, 44, 38, 92, 61, 28, 92, 20] The key is 32 The resultant list is : [2, 9, 9, 9, 9, 9, 2, 9, 2]
A list of integers is defined and is displayed on the console.
A value for key is defined and is displayed on the console.
The 'low' and 'high' variables are assigned values.
An empty list is defined.
The original list is iterated over, and every element is compared with the key.
If the element is greater, the 'high' variable is appended to the empty list.
Otherwise, the 'low' variable is appended to the empty list.
This is displayed as output on the console.
- Python Program to replace list elements within a range with a given number
- Add list elements with a multi-list based on index in Python
- Java Program to Replace Elements in a List
- Python Program to print strings based on the list of prefix
- Python program to convert a list to a set based on a common element
- Program to find the kth missing number from a list of elements in Python
- C# Program to filter array elements based on a predicate
- Python program to replace all Characters of a List except the given character
- Python Program to Find Number of Occurrences of All Elements in a Linked List
- How to replace the values in a matrix with another value based on a condition in R?
- Python program to sort a List according to the Length of the Elements?
- Program to count number of elements in a list that contains odd number of digits in Python
- Python program to find Tuples with positive elements in a List of tuples
- Python Program to Search the Number of Times a Particular Number Occurs in a List
- Sort a list according to the Length of the Elements in Python program