- Trending Categories
- Data Structure
- Operating System
- MS Excel
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- 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.
Kickstart Your Career
Get certified by completing the courseGet Started