When it is required to extract rows with even length strings, a list comprehension along with the ‘all’ operator and ‘%’ operator is used.
Below is a demonstration of the same −
my_list = [["python", "is", "best"], ["best", "good", "python"], ["is", "better"], ["for", "coders"]] print("The list is :") print(my_list) my_result = [row for row in my_list if all(len(element ) % 2 == 0 for element in row)] print("The resultant list is :") print(my_result)
The list is : [['python', 'is', 'best'], ['best', 'good', 'python'], ['is', 'better'], ['for', 'coders']] The resultant list is : [['python', 'is', 'best'], ['best', 'good', 'python'], ['is', 'better']]
A list of list with strings is defined and is displayed on the console.
A list comprehension is used to iterate over the elements of the list.
It checks to see if the elements have even length using the ‘all’ operator and modulus operator.
If yes, it is stored in a list, and assigned to a variable.
This variable is displayed as output on the console.