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.

Example

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)

Output

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]

Explanation

  • 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.

Updated on: 16-Sep-2021

304 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements