Python – Test for desired String Lengths

PythonServer Side ProgrammingProgramming

When it is required to test for desired string lengths, a simple iteration, and the ‘len’ method is used.


Below is a demonstration of the same −

my_list = ["python", 'is', 'fun', 'to', 'learn', 'Will', 'how']

print("The list is :")
length_list = [6, 2, 3, 2, 5, 4, 3]

my_result = True
for index in range(len(my_list)):

   if len(my_list[index]) != length_list[index]:
      my_result = False

print("The result is :")

if(my_result == True):
   print("All the strings are of required lengths")
   print("All the strings are not of required lengths")


The list is :
['python', 'is', 'fun', 'to', 'learn', 'Will', 'how']
The result is :
All the strings are of required lengths


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

  • A list of integers is also defined.

  • A Boolean value is set to ‘True’.

  • The string list is iterated over, and if the respective index’s length is not equal to the value in the integer list’s same index, the Boolean value is set to False.

  • The control breaks out of the loop.

  • Depending on the Boolean value, relevant message is displayed on the console.

Published on 08-Sep-2021 06:25:19