Python – Remove characters greater than K

When it is required to remove characters, which are greater than ‘K’, a simple iteration is used along with the ‘ord’ (Unicode representation) method.

Below is a demonstration of the same −


 Live Demo

my_list = ["python", "is", "easy", "to", "learn"]

print("The list is :")

K = 9
print("The value of K is ")

my_result = []

for element in my_list:
   result_string = ''
   for sub in element:

      if (ord(sub) - 97 <= K):
         result_string += sub

print("The resultant list is :")


The list is :
['python', 'is', 'easy', 'to', 'learn']
The value of K is
The resultant list is :
['h', 'i', 'ea', '', 'ea']


  • A list with strings is defined and is displayed on the console.

  • The value for K is defined and is displayed on the console.

  • An empty list is defined.

  • The list is iterated over, and an empty string is created.

  • The elements are checked to see if difference between Unicode representation of the element and 97 is less than K.

  • If yes, the element is appended to empty string.

  • Otherwise, this string is appended to the empty list.

  • This is displayed as output on the console.