
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extract Rows with Even Length Strings in Python
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 −
Example
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)
Output
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']]
Explanation
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.
Advertisements